refactor(JsonTools): 规范化页面组件目录结构

- 将子组件移至 components/ 子目录(JsonDiffInput、DiffResult、JsonFormatSection、JsonConvertSection、DiffNavigator、JsonTree)
- 将 diffEngine.ts 工具函数移至 src/utils/
- 提取 ConvertFunction/ConvertResult 类型到 types.ts,解决循环依赖
- 创建 __tests__/ 目录结构
- 更新所有相关导入路径

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
雨霖铃
2026-06-10 20:39:40 +08:00
parent 30d3561726
commit 016173a9c5
12 changed files with 33 additions and 20 deletions
@@ -0,0 +1,87 @@
import React from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useI18n } from '@/utils/chromeI18n';
import { cn } from '@/lib/utils';
export interface DiffNavigatorProps extends React.HTMLAttributes<HTMLDivElement> {
total: number;
/** 0-based index */
currentIndex: number;
onPrev: () => void;
onNext: () => void;
}
export default function DiffNavigator({
total,
currentIndex,
onPrev,
onNext,
className,
...props
}: DiffNavigatorProps) {
const { t } = useI18n('jsonDiff');
const isFirst = currentIndex <= 0;
const isLast = currentIndex >= total - 1;
if (total === 0) {
return (
<div
className={cn(
'flex items-center justify-center gap-3 px-4 py-2 rounded-lg border border-border bg-muted/30 select-none',
className,
)}
{...props}
>
<span className="text-xs font-semibold text-muted-foreground/90">
{t('jsonDiff:noDiffs')}
</span>
</div>
);
}
return (
<div
className={cn(
'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 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',
)}
>
<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 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',
)}
>
<ChevronRight className="h-4 w-4" />
</button>
</div>
);
}
@@ -0,0 +1,231 @@
import React from 'react';
import { useI18n } from '@/utils/chromeI18n';
import { cn } from '@/lib/utils';
import JsonTree from './JsonTree';
import type { DiffNode, DiffResult as DiffResultType, DiffType, ViewMode } from '../types';
export interface DiffResultProps extends React.HTMLAttributes<HTMLDivElement> {
result: DiffResultType;
viewMode: ViewMode;
activePath?: string;
}
export default function DiffResult({
result,
viewMode,
activePath,
className,
...props
}: DiffResultProps) {
const { t } = useI18n('jsonDiff');
if (viewMode === 'sideBySide') {
return (
<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} />
</div>
<div className="flex-1 min-w-0">
<SectionLabel text={t('jsonDiff:rightLabel')} />
<JsonTree node={result.root} side="right" activePath={activePath} />
</div>
</div>
);
}
return (
<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} />
</div>
);
}
const SectionLabel = ({ text }: { text: string }) => (
<span className="block mb-2 text-[10px] font-bold tracking-wider text-muted-foreground/80 uppercase px-0.5 select-none">
{text}
</span>
);
const formatPrimitive = (v: unknown): string => {
if (v === undefined) return 'undefined';
if (v === null) return 'null';
if (typeof v === 'string') return JSON.stringify(v);
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
return JSON.stringify(v);
};
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 ' ';
};
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 {
node: DiffNode;
depth: number;
activePath?: string;
}
const UnifiedView = ({ node, depth, activePath }: UnifiedViewProps) => {
const isRoot = depth === 0;
const hasChildren = Array.isArray(node.children) && node.children.length > 0;
const isContainer =
hasChildren || isContainerType(node.oldValue) || isContainerType(node.newValue);
const keyLabel = isRoot ? '' : `${node.key}: `;
if (!isContainer) {
if (node.type === 'modified') {
return (
<>
<UnifiedRow
depth={depth}
type="removed"
text={`${keyLabel}${formatPrimitive(node.oldValue)}`}
active={activePath === node.path}
/>
<UnifiedRow
depth={depth}
type="added"
text={`${keyLabel}${formatPrimitive(node.newValue)}`}
active={activePath === node.path}
/>
</>
);
}
const value = node.type === 'added' ? node.newValue : node.oldValue;
return (
<UnifiedRow
depth={depth}
type={node.type}
text={`${keyLabel}${formatPrimitive(value)}`}
active={activePath === node.path}
/>
);
}
// 容器节点整块渲染处理
if (node.type === 'added') {
return (
<UnifiedRow
depth={depth}
type="added"
text={`${keyLabel}${stringifyMultiline(node.newValue, depth)}`}
active={activePath === node.path}
multiline
/>
);
}
if (node.type === 'removed') {
return (
<UnifiedRow
depth={depth}
type="removed"
text={`${keyLabel}${stringifyMultiline(node.oldValue, depth)}`}
active={activePath === node.path}
multiline
/>
);
}
const isArr = Array.isArray(node.oldValue) || Array.isArray(node.newValue);
const open = isArr ? '[' : '{';
const close = isArr ? ']' : '}';
return (
<>
<UnifiedRow depth={depth} type="unchanged" text={`${keyLabel}${open}`} />
{node.children?.map((child) => (
<UnifiedView key={child.path} node={child} depth={depth + 1} activePath={activePath} />
))}
<UnifiedRow depth={depth} type="unchanged" text={close} />
</>
);
};
interface UnifiedRowProps {
depth: number;
type: DiffType;
text: string;
active?: boolean;
multiline?: boolean;
}
const UnifiedRow = ({ depth, type, text, active, multiline }: UnifiedRowProps) => {
const currentTheme = typeThemeMap[type] || typeThemeMap.unchanged;
return (
<div
className={cn(
'flex items-start w-full font-mono py-0.5 select-text group',
currentTheme.bg,
currentTheme.text,
active &&
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1 before:bg-blue-500',
)}
style={{
paddingLeft: `${Math.max(0.5, depth * 1.25)}rem`,
paddingRight: '0.5rem',
}}
>
<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>
);
};
const stringifyMultiline = (v: unknown, depth: number): string => {
try {
const json = JSON.stringify(v, null, 2);
if (!json) return formatPrimitive(v);
const indent = ' '.repeat(depth);
return json
.split('\n')
.map((line, idx) => (idx === 0 ? line : indent + line))
.join('\n');
} catch {
return formatPrimitive(v);
}
};
@@ -0,0 +1,124 @@
import React, { useEffect, useMemo, useState } from 'react';
import { useI18n } from '@/utils/chromeI18n';
import { formatBytes } from '@/utils/format';
import { CopyButton } from '@/components/CopyButton';
import TextInputArea from '@/components/TextInputArea';
import { validateJson } from '@/utils/jsonFormatter';
import { cn } from '@/lib/utils';
import type { ConvertFunction, ConvertResult } from '../types';
interface JsonConvertSectionProps extends React.HTMLAttributes<HTMLDivElement> {
translationPrefix: string;
convertFunction: ConvertFunction;
}
export default function JsonConvertSection({
translationPrefix,
convertFunction,
className,
...props
}: JsonConvertSectionProps) {
const { t } = useI18n('jsonFormat');
const [input, setInput] = useState('');
const [debouncedInput, setDebouncedInput] = useState('');
const pk = translationPrefix;
// Debounce input
useEffect(() => {
const handle = setTimeout(() => {
setDebouncedInput(input);
}, 250);
return () => clearTimeout(handle);
}, [input]);
const error = useMemo(() => {
return validateJson(debouncedInput);
}, [debouncedInput]);
const conversionPipeline = useMemo(() => {
const trimmed = debouncedInput.trim();
if (!trimmed || error) return null;
try {
return convertFunction(debouncedInput);
} catch (e) {
// 捕获可能从外部转换器(如 YAML.stringify)中抛出的底层异常
return {
isRuntimeError: true,
errorMessage: e instanceof Error ? e.message : String(e),
};
}
}, [debouncedInput, error, convertFunction]);
const runtimeError =
conversionPipeline && 'isRuntimeError' in conversionPipeline
? conversionPipeline.errorMessage
: null;
const result =
conversionPipeline && !('isRuntimeError' in conversionPipeline)
? (conversionPipeline as ConvertResult)
: null;
return (
<div className={cn('w-full flex flex-col gap-4', className)} {...props}>
{/* 输入区 */}
<TextInputArea
placeholder={t(`jsonFormat:${pk}InputPlaceholder`)}
value={input}
onChange={setInput}
externalError={error || runtimeError || undefined}
showClear={true}
allowCopy={true}
minRows={7}
maxRows={14}
onClear={() => setInput('')}
/>
{/* Result display */}
{result && result.output ? (
<div className="relative rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden">
<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`)}
</span>
<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">
{formatBytes(result.originalBytes)}
</span>
</span>
<span className="text-border/60">|</span>
<span>
{t('jsonFormat:formattedSize')}:{' '}
<span className="font-semibold text-foreground/80">
{formatBytes(result.outputBytes)}
</span>
</span>
</div>
</div>
<CopyButton
text={result.output}
className="h-6 w-6 rounded-md border text-muted-foreground"
/>
</div>
<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}
</div>
</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-[120px] select-none">
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[240px] leading-relaxed">
{error ? t('jsonFormat:fixErrorHint') : t(`jsonFormat:${pk}EmptyHint`)}
</p>
</div>
)}
</div>
);
}
@@ -0,0 +1,42 @@
import React from 'react';
import TextInputArea from '@/components/TextInputArea';
import { cn } from '@/lib/utils';
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({
label,
placeholder,
value,
onChange,
error,
minRows = 10,
className,
...props
}: JsonDiffInputProps) {
return (
<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}
</span>
<TextInputArea
value={value}
onChange={onChange}
placeholder={placeholder}
minRows={minRows}
maxRows={16}
externalError={error ?? undefined}
showClear={true}
allowCopy={true}
/>
</div>
);
}
@@ -0,0 +1,163 @@
import { useEffect, useMemo, useState } from 'react';
import { useI18n } from '@/utils/chromeI18n';
import {
formatJson,
type JsonFormatOptions,
type JsonFormatResult,
validateJson,
} from '@/utils/jsonFormatter';
import { formatBytes } from '@/utils/format';
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';
export default function JsonFormatSection() {
const { t } = useI18n('jsonFormat');
const [input, setInput] = useState('');
const [debouncedInput, setDebouncedInput] = useState('');
const [indentSize, setIndentSize] = useState<number>(2);
const [sortKeys, setSortKeys] = useState(false);
// Debounce input
useEffect(() => {
const handle = setTimeout(() => {
setDebouncedInput(input);
}, 250);
return () => clearTimeout(handle);
}, [input]);
const error = useMemo(() => {
return validateJson(debouncedInput);
}, [debouncedInput]);
// Real-time formatting pipeline
const formattedPipeline = useMemo(() => {
const trimmed = debouncedInput.trim();
if (!trimmed || error) return null;
try {
const options: JsonFormatOptions = { indentSize, sortKeys };
return formatJson(debouncedInput, options);
} catch (e) {
return {
isRuntimeError: true,
errorMessage: e instanceof SyntaxError ? e.message : String(e),
};
}
}, [debouncedInput, error, indentSize, sortKeys]);
const runtimeError =
formattedPipeline && 'isRuntimeError' in formattedPipeline
? formattedPipeline.errorMessage
: null;
const result =
formattedPipeline && !('isRuntimeError' in formattedPipeline)
? (formattedPipeline as JsonFormatResult)
: null;
return (
<div className="w-full flex flex-col gap-4">
{/* 工具控制栏 */}
<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"
>
<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"
>
{t('jsonFormat:sortKeys')}
</Label>
</div>
</div>
</div>
{/* 满血版输入终端 */}
<TextInputArea
placeholder={t('jsonFormat:inputPlaceholder')}
value={input}
onChange={setInput}
externalError={error || runtimeError || undefined}
showClear={true}
allowCopy={true}
minRows={8}
maxRows={15}
onClear={() => setInput('')}
/>
{/* 格式化结果流面板展示 */}
{result && result.formatted ? (
<div className="relative rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden">
{/* 结果栏头部 */}
<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')}
</span>
<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">
{formatBytes(result.originalBytes)}
</span>
</span>
<span className="text-border/60">|</span>
<span>
{t('jsonFormat:formattedSize')}:{' '}
<span className="font-semibold text-foreground/80">
{formatBytes(result.formattedBytes)}
</span>
</span>
</div>
</div>
<CopyButton
text={result.formatted}
className="h-6 w-6 rounded-md border text-muted-foreground"
/>
</div>
<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}
</div>
</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-[120px] select-none">
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[240px] leading-relaxed">
{error ? t('jsonFormat:fixErrorHint') : t('jsonFormat:emptyHint')}
</p>
</div>
)}
</div>
);
}
+261
View File
@@ -0,0 +1,261 @@
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';
export interface JsonTreeProps extends React.HTMLAttributes<HTMLDivElement> {
node: DiffNode;
side: TreeSide;
defaultExpandDepth?: number;
activePath?: string;
}
interface NodeRowProps {
node: DiffNode;
side: TreeSide;
depth: number;
defaultExpandDepth: number;
activePath?: string;
isLastChild: boolean;
}
const formatPrimitive = (v: unknown): string => {
if (v === null) return 'null';
if (typeof v === 'string') return JSON.stringify(v);
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
return JSON.stringify(v);
};
const shouldRenderOnSide = (type: DiffType, side: TreeSide): boolean => {
if (type === 'added') return side === 'right';
if (type === 'removed') return side === 'left';
return true;
};
const getValueForSide = (node: DiffNode, side: TreeSide): unknown => {
return side === 'left' ? node.oldValue : node.newValue;
};
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 = 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 = 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;
// 当激活路径精准定位到本行时,平滑滚动至容器中心
useEffect(() => {
if (activePath === node.path) {
rowRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [activePath, node.path]);
// 占位空行分支:必须加 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` }}
>
·
</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;
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 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>
)}
{/* 大容器收尾行 */}
{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 ? '' : ','}
</div>
)}
</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',
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>
);
},
);
NodeRow.displayName = 'NodeRow';
export default function JsonTree({
node,
side,
defaultExpandDepth = 2,
activePath,
className,
...props
}: JsonTreeProps) {
return (
/* 最外层承载器:统一收拢至标准的 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={side}
depth={0}
defaultExpandDepth={defaultExpandDepth}
activePath={activePath}
isLastChild
/>
</div>
);
}
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 '';
};