Compare commits

..

7 Commits

Author SHA1 Message Date
rsgltzyd bc851414b4 refactor(utils): 将 diffNode 实现从递归改为迭代遍历 2026-07-10 23:22:46 +08:00
rsgltzyd e7639fef72 style: 增强 SwitchButtonGroup 的交互样式并移除冗余属性 2026-07-09 23:51:15 +08:00
rsgltzyd a8c0809363 refactor: 优化组件导出并移除未使用的组件并清理冗余代码 2026-07-09 23:38:14 +08:00
rsgltzyd fdbb51754d refactor: 为 SelectItem 组件添加 cursor-pointer 类以改善用户体验 2026-07-09 23:36:52 +08:00
rsgltzyd f0c3d9c173 refactor: 更新组件引用类型为 ComponentRef,以提高类型安全性 2026-07-09 23:28:59 +08:00
rsgltzyd 14d85e5265 refactor: 更新样式和组件结构以提升一致性和可读性
- 在 utils.ts 中引入 twMerge 以合并 Tailwind 类。
- 在 ConverterForm.tsx 中简化类名,移除冗余样式。
- 在 LiveClock.tsx 中调整样式,优化文本显示。
- 在 ResultView.tsx 中更新布局和样式,提升视觉效果。
2026-07-08 23:24:54 +08:00
rsgltzyd c8c3c88d99 refactor: 移除 PageSkeleton 组件及相关测试,更新 RouterContainer 以简化加载逻辑 2026-07-06 20:05:52 +08:00
19 changed files with 274 additions and 290 deletions
-41
View File
@@ -1,41 +0,0 @@
/**
* PageSkeleton 组件 - 页面加载骨架屏
*
* 用于 Suspense fallback 和初始加载状态,提供平滑的视觉过渡
* 避免白屏闪烁,减少布局偏移
*/
/**
* 工具页面骨架屏
*/
function ToolPageSkeleton() {
return (
<div className="p-5">
{/* 标题区域 */}
<div className="w-44 h-7 bg-muted rounded animate-pulse mb-4" />
{/* 输入区域 */}
<div className="w-full h-[120px] bg-muted rounded-xl animate-pulse mb-4" />
{/* 控制栏 */}
<div className="flex gap-2 mb-4">
<div className="w-24 h-9 bg-muted rounded-lg animate-pulse" />
<div className="w-20 h-9 bg-muted rounded-lg animate-pulse" />
<div className="flex-1" />
<div className="w-24 h-9 bg-muted rounded-lg animate-pulse" />
</div>
{/* 结果区域 */}
<div className="w-full h-[160px] bg-muted rounded-xl animate-pulse" />
</div>
);
}
/**
* 页面加载骨架屏
*/
export default function PageSkeleton() {
return <ToolPageSkeleton />;
}
PageSkeleton.displayName = 'PageSkeleton';
+2 -3
View File
@@ -5,8 +5,8 @@
## 组件列表 ## 组件列表
| 组件 | 用途 | | 组件 | 用途 |
| ----------------------- | ------------------------------------------------------------------------------ | | ----------------------- | ------------------------------------------------------------------------------------------------------ |
| `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界和骨架屏 | | `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界 |
| `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 | | `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 |
| `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 | | `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 |
| `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 | | `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 |
@@ -17,7 +17,6 @@
| `GlobalSnackbar.tsx` | 全局消息提示组件 + Context Provider,支持受控/Hook/全局单例三种使用方式 | | `GlobalSnackbar.tsx` | 全局消息提示组件 + Context Provider,支持受控/Hook/全局单例三种使用方式 |
| `ErrorBoundary.tsx` | 全局错误边界(类组件),捕获子组件树 JS 错误并展示友好错误页面 | | `ErrorBoundary.tsx` | 全局错误边界(类组件),捕获子组件树 JS 错误并展示友好错误页面 |
| `PageErrorBoundary.tsx` | 页面级错误边界,适配 shadcn 暗黑模式,支持 `resetKey` 自动恢复 | | `PageErrorBoundary.tsx` | 页面级错误边界,适配 shadcn 暗黑模式,支持 `resetKey` 自动恢复 |
| `PageSkeleton.tsx` | 页面骨架屏,提供 `dashboard``tool` 两种变体,用于 Suspense fallback |
## 使用约定 ## 使用约定
+1 -2
View File
@@ -4,7 +4,6 @@ import { useRouter } from '@/providers/RouterProvider';
import type { PageType } from '@/types/storage'; import type { PageType } from '@/types/storage';
import { type ComponentType, useEffect, useState } from 'react'; import { type ComponentType, useEffect, useState } from 'react';
import PageErrorBoundary from '@/components/PageErrorBoundary'; import PageErrorBoundary from '@/components/PageErrorBoundary';
import PageSkeleton from '@/components/PageSkeleton';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { AlertTriangle } from 'lucide-react'; import { AlertTriangle } from 'lucide-react';
@@ -30,7 +29,7 @@ function LoadedPage({ pageKey }: { pageKey: PageType }) {
}, [pageKey]); }, [pageKey]);
if (!Page) { if (!Page) {
return <PageSkeleton />; return <div className="flex-1" aria-hidden="true" />;
} }
return <Page />; return <Page />;
+4 -5
View File
@@ -15,7 +15,6 @@ export interface SwitchButtonGroupProps<T extends string | number = string> exte
options: SwitchOption<T>[]; options: SwitchOption<T>[];
onChange: (value: T) => void; onChange: (value: T) => void;
size?: 'small' | 'medium' | 'large'; size?: 'small' | 'medium' | 'large';
buttonClassName?: string;
} }
const SIZE_CLASSES = { const SIZE_CLASSES = {
@@ -24,8 +23,10 @@ const SIZE_CLASSES = {
large: 'text-base h-11 px-4 py-2 rounded-lg', large: 'text-base h-11 px-4 py-2 rounded-lg',
} as const; } as const;
const SELECTED_CLASSES = 'bg-background text-foreground shadow-sm font-semibold fade-in-zoom-95'; const SELECTED_CLASSES =
const UNSELECTED_CLASSES = 'hover:bg-background/50 hover:text-foreground/80'; 'bg-background text-foreground shadow-sm font-semibold fade-in-zoom-95 hover:shadow-md active:scale-[0.98] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-muted';
const UNSELECTED_CLASSES =
'hover:bg-background/50 hover:text-foreground/80 active:scale-[0.98] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-muted';
export default function SwitchButtonGroup<T extends string | number = string>({ export default function SwitchButtonGroup<T extends string | number = string>({
value, value,
@@ -33,7 +34,6 @@ export default function SwitchButtonGroup<T extends string | number = string>({
onChange, onChange,
size = 'medium', size = 'medium',
className, className,
buttonClassName,
...props ...props
}: SwitchButtonGroupProps<T>) { }: SwitchButtonGroupProps<T>) {
return ( return (
@@ -54,7 +54,6 @@ export default function SwitchButtonGroup<T extends string | number = string>({
'flex-1 transition-all', 'flex-1 transition-all',
SIZE_CLASSES[size], SIZE_CLASSES[size],
value === option.value ? SELECTED_CLASSES : UNSELECTED_CLASSES, value === option.value ? SELECTED_CLASSES : UNSELECTED_CLASSES,
buttonClassName,
)} )}
> >
{option.label} {option.label}
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest';
import { render } from '@testing-library/react';
import PageSkeleton from '@/components/PageSkeleton';
describe('PageSkeleton 组件', () => {
describe('渲染测试', () => {
it('应渲染工具页面骨架', () => {
const { container } = render(<PageSkeleton />);
const skeletons = container.querySelectorAll('.animate-pulse');
expect(skeletons.length).toBeGreaterThan(0);
});
});
describe('布局结构测试', () => {
it('工具骨架屏应有内边距', () => {
const { container } = render(<PageSkeleton />);
const toolContainer = container.firstChild as HTMLElement;
expect(toolContainer).toHaveClass('p-5');
});
});
describe('骨架屏元素测试', () => {
it('工具骨架屏应包含动画脉冲效果', () => {
const { container } = render(<PageSkeleton />);
const skeletons = container.querySelectorAll('.animate-pulse');
expect(skeletons.length).toBeGreaterThan(0);
});
});
});
+2 -2
View File
@@ -22,11 +22,11 @@ const badgeVariants = cva(
}, },
); );
export interface BadgeProps interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {} extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) { function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />; return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
} }
export { Badge, badgeVariants }; export { Badge };
+1 -1
View File
@@ -46,4 +46,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
); );
Button.displayName = 'Button'; Button.displayName = 'Button';
export { Button, buttonVariants }; export { Button };
+1 -1
View File
@@ -5,7 +5,7 @@ import { Check } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
const Checkbox = React.forwardRef< const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>, React.ComponentRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root> React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root <CheckboxPrimitive.Root
+4 -4
View File
@@ -12,7 +12,7 @@ const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close; const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef< const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>, React.ComponentRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay> React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay <DialogPrimitive.Overlay
@@ -33,7 +33,7 @@ interface DialogContentProps extends React.ComponentPropsWithoutRef<
} }
const DialogContent = React.forwardRef< const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>, React.ComponentRef<typeof DialogPrimitive.Content>,
DialogContentProps DialogContentProps
>(({ className, children, showCloseButton = true, ...props }, ref) => ( >(({ className, children, showCloseButton = true, ...props }, ref) => (
<DialogPortal> <DialogPortal>
@@ -72,7 +72,7 @@ const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivEleme
DialogFooter.displayName = 'DialogFooter'; DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef< const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>, React.ComponentRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title> React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<DialogPrimitive.Title <DialogPrimitive.Title
@@ -84,7 +84,7 @@ const DialogTitle = React.forwardRef<
DialogTitle.displayName = DialogPrimitive.Title.displayName; DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef< const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>, React.ComponentRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description> React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<DialogPrimitive.Description <DialogPrimitive.Description
+1 -1
View File
@@ -9,7 +9,7 @@ const labelVariants = cva(
); );
const Label = React.forwardRef< const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>, React.ComponentRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants> React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} /> <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
+7 -30
View File
@@ -10,7 +10,7 @@ const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value; const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef< const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>, React.ComponentRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger> React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => ( >(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger <SelectPrimitive.Trigger
@@ -30,7 +30,7 @@ const SelectTrigger = React.forwardRef<
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName; SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef< const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>, React.ComponentRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton> React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton <SelectPrimitive.ScrollUpButton
@@ -44,7 +44,7 @@ const SelectScrollUpButton = React.forwardRef<
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName; SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef< const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>, React.ComponentRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton> React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton <SelectPrimitive.ScrollDownButton
@@ -58,7 +58,7 @@ const SelectScrollDownButton = React.forwardRef<
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName; SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef< const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>, React.ComponentRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => ( >(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal> <SelectPrimitive.Portal>
@@ -90,7 +90,7 @@ const SelectContent = React.forwardRef<
SelectContent.displayName = SelectPrimitive.Content.displayName; SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef< const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>, React.ComponentRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label> React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<SelectPrimitive.Label <SelectPrimitive.Label
@@ -102,7 +102,7 @@ const SelectLabel = React.forwardRef<
SelectLabel.displayName = SelectPrimitive.Label.displayName; SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef< const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>, React.ComponentRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => ( >(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item <SelectPrimitive.Item
@@ -124,27 +124,4 @@ const SelectItem = React.forwardRef<
)); ));
SelectItem.displayName = SelectPrimitive.Item.displayName; SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef< export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem };
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
+1 -1
View File
@@ -4,7 +4,7 @@ import * as SwitchPrimitives from '@radix-ui/react-switch';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
const Switch = React.forwardRef< const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>, React.ComponentRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root> React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<SwitchPrimitives.Root <SwitchPrimitives.Root
+2 -1
View File
@@ -1,5 +1,6 @@
import { type ClassValue, clsx } from 'clsx'; import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return clsx(inputs); return twMerge(clsx(inputs));
} }
@@ -84,7 +84,11 @@ export default function GeneratorConfig({ generator, params, onChange }: Generat
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{param.options?.map((option) => ( {param.options?.map((option) => (
<SelectItem key={String(option.value)} value={String(option.value)}> <SelectItem
key={String(option.value)}
value={String(option.value)}
className="cursor-pointer"
>
{option.label} {option.label}
</SelectItem> </SelectItem>
))} ))}
@@ -41,10 +41,7 @@ export default function ConverterForm({
placeholder={INPUT_PLACEHOLDERS[mode]} placeholder={INPUT_PLACEHOLDERS[mode]}
value={input} value={input}
onChange={(e) => setInput(e.target.value)} onChange={(e) => setInput(e.target.value)}
className={cn( className={cn('h-10', error && 'border-destructive')}
'font-mono font-semibold h-10 shadow-sm placeholder:text-muted-foreground/60 focus:bg-background',
error && 'border-destructive focus-visible:ring-destructive',
)}
/> />
{error && <p className="text-destructive text-xs font-medium px-0.5">{error}</p>} {error && <p className="text-destructive text-xs font-medium px-0.5">{error}</p>}
@@ -60,16 +57,13 @@ export default function ConverterForm({
/> />
<Select value={zone} onValueChange={(v: string) => setZone(v as ZoneType)}> <Select value={zone} onValueChange={(v: string) => setZone(v as ZoneType)}>
<SelectTrigger className="flex-1 font-mono font-semibold h-9 shadow-sm bg-background"> <SelectTrigger>
<SelectValue placeholder="选择时区" /> <SelectValue placeholder="选择时区" />
</SelectTrigger> </SelectTrigger>
<SelectContent className="max-h-64 font-mono">
<SelectContent className="max-h-64">
{ZONES.map((z) => ( {ZONES.map((z) => (
<SelectItem <SelectItem key={z} value={z} className="cursor-pointer">
key={z}
value={z}
className="text-xs font-semibold focus:bg-accent cursor-pointer"
>
{z} {z}
</SelectItem> </SelectItem>
))} ))}
+8 -11
View File
@@ -1,4 +1,5 @@
import React, { useEffect, useState } from 'react'; import type { HTMLAttributes } from 'react';
import { useEffect, useState } from 'react';
import { Clock } from 'lucide-react'; import { Clock } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { CopyButton } from '@/components/CopyButton'; import { CopyButton } from '@/components/CopyButton';
@@ -7,7 +8,7 @@ import { msToUnit } from '../constants';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
interface LiveClockProps extends React.HTMLAttributes<HTMLDivElement> { interface LiveClockProps extends HTMLAttributes<HTMLDivElement> {
unit: UnitType; unit: UnitType;
onUseNow: (val: number) => void; onUseNow: (val: number) => void;
} }
@@ -28,18 +29,14 @@ export default function LiveClock({ unit, onUseNow, className, ...props }: LiveC
return ( return (
<div <div
className={cn( className={cn(
'flex items-center gap-3 px-3 h-10 rounded-lg border border-border/80 bg-secondary/50', 'flex items-center gap-3 px-3 h-10 rounded-lg font-bold text-[12px] border px-[20px]',
className, className,
)} )}
{...props} {...props}
> >
<span className="text-muted-foreground font-bold text-[10px] uppercase tracking-wider whitespace-nowrap shrink-0 selection:bg-transparent select-none"> <span></span>
</span>
<span className="flex-1 font-mono font-bold text-foreground text-sm tracking-tight leading-none truncate tabular-nums"> <span className="flex-1 text-sm ">{text}</span>
{text}
</span>
<Button <Button
type="button" type="button"
@@ -50,12 +47,12 @@ export default function LiveClock({ unit, onUseNow, className, ...props }: LiveC
title="填充到下方" title="填充到下方"
variant="ghost" variant="ghost"
size="icon" size="icon"
className="h-7 w-7 text-muted-foreground hover:text-foreground" className="h-7 w-7"
> >
<Clock className="w-3.5 h-3.5" /> <Clock className="w-3.5 h-3.5" />
</Button> </Button>
<CopyButton text={text} tooltip="复制时间戳" className="h-7 w-7 rounded-md border" /> <CopyButton text={text} tooltip="复制时间戳" className="h-7 w-7" />
</div> </div>
); );
} }
@@ -34,16 +34,15 @@ export default function ResultView({
</span> </span>
<div className="bg-card text-card-foreground border border-border p-4 sm:p-5 rounded-xl relative shadow-sm flex justify-between items-center gap-4 focus-within:ring-1 focus-within:ring-ring"> <div className="bg-card border p-4 rounded-lg flex items-center gap-3 justify-between">
<span className="font-mono font-extrabold text-foreground break-all text-xl sm:text-2xl tracking-tight leading-tight select-all tabular-nums"> <span className="break-all text-lg select-all flex-1">{result}</span>
{result}
</span>
<CopyButton <CopyButton
text={result} text={result}
tooltip="复制结果" tooltip="复制结果"
variant="ghost" variant="ghost"
size="icon" size="icon"
className="h-7 w-7 text-muted-foreground hover:text-foreground" className="h-7 w-7"
/> />
</div> </div>
</div> </div>
+201 -112
View File
@@ -19,7 +19,6 @@ const buildPath = (parent: string, key: string, isArrayChild: boolean): string =
} }
const needsEscaping = key.includes('.') || key.includes('[') || key.includes(' '); const needsEscaping = key.includes('.') || key.includes('[') || key.includes(' ');
const formattedKey = needsEscaping ? `["${key}"]` : `.${key}`; const formattedKey = needsEscaping ? `["${key}"]` : `.${key}`;
return parent === ROOT_PATH ? `${ROOT_PATH}${formattedKey}` : `${parent}${formattedKey}`; return parent === ROOT_PATH ? `${ROOT_PATH}${formattedKey}` : `${parent}${formattedKey}`;
}; };
@@ -30,104 +29,48 @@ const primitiveEqual = (a: unknown, b: unknown): boolean => {
return a === b; return a === b;
}; };
const diffNode = ( // ---------- 迭代遍历框架 ----------
interface StackFrame {
left: MaybeMissing;
right: MaybeMissing;
key: string;
path: string;
/** 子节点数量(组装时从 resultStack 弹出) */
childCount: number;
/** 是否已展开 */
assembled: boolean;
/** 分类结果缓存 */
leftObj: boolean;
rightObj: boolean;
leftArr: boolean;
rightArr: boolean;
leftIsContainer: boolean;
rightIsContainer: boolean;
}
const createLeafNode = (
key: string,
path: string,
type: DiffNode['type'],
oldValue: MaybeMissing,
newValue: MaybeMissing,
): DiffNode => ({
key,
type,
oldValue: oldValue === SENTINEL ? undefined : oldValue,
newValue: newValue === SENTINEL ? undefined : newValue,
path,
isLeaf: true,
hasDiffInChildren: false,
});
const classifyPrimitive = (
left: MaybeMissing, left: MaybeMissing,
right: MaybeMissing, right: MaybeMissing,
key: string, key: string,
path: string, path: string,
diffPaths: string[], ): DiffNode | null => {
): DiffNode => {
if (left === SENTINEL && right !== SENTINEL) {
diffPaths.push(path);
return {
key,
type: 'added',
oldValue: undefined,
newValue: right,
path,
isLeaf: !isObject(right) && !isArray(right),
hasDiffInChildren: false,
};
}
if (right === SENTINEL && left !== SENTINEL) {
diffPaths.push(path);
return {
key,
type: 'removed',
oldValue: left,
newValue: undefined,
path,
isLeaf: !isObject(left) && !isArray(left),
hasDiffInChildren: false,
};
}
const leftObj = isObject(left);
const rightObj = isObject(right);
const leftArr = isArray(left);
const rightArr = isArray(right);
if (leftObj && rightObj) {
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;
children.push(diffNode(l, r, k, childPath, diffPaths));
});
const hasDiffInChildren = children.some((c) => c.type !== 'unchanged' || c.hasDiffInChildren);
return {
key,
type: hasDiffInChildren ? 'modified' : 'unchanged',
oldValue: left,
newValue: right,
children,
path,
isLeaf: false,
hasDiffInChildren,
};
}
if (leftArr && rightArr) {
const len = Math.max(left.length, right.length);
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[i] = diffNode(l, r, k, childPath, diffPaths);
}
const hasDiffInChildren = children.some((c) => c.type !== 'unchanged' || c.hasDiffInChildren);
return {
key,
type: hasDiffInChildren ? 'modified' : 'unchanged',
oldValue: left,
newValue: right,
children,
path,
isLeaf: false,
hasDiffInChildren,
};
}
const leftIsContainer = leftObj || leftArr;
const rightIsContainer = rightObj || rightArr;
if (!leftIsContainer && !rightIsContainer) {
if (left === null || right === null) { if (left === null || right === null) {
if (left === null && right === null) { if (left === null && right === null) {
return { return {
@@ -140,8 +83,9 @@ const diffNode = (
hasDiffInChildren: false, hasDiffInChildren: false,
}; };
} }
} else if (typeof left === typeof right) { return null;
if (primitiveEqual(left, right)) { }
if (typeof left === typeof right && primitiveEqual(left, right)) {
return { return {
key, key,
type: 'unchanged', type: 'unchanged',
@@ -152,27 +96,172 @@ const diffNode = (
hasDiffInChildren: false, hasDiffInChildren: false,
}; };
} }
} return null;
}
diffPaths.push(path);
return {
key,
type: 'modified',
oldValue: left,
newValue: right,
path,
isLeaf: !leftIsContainer && !rightIsContainer,
hasDiffInChildren: false,
};
}; };
/** /**
* 比较两个 JSON 值的差异 * 合并对象 key:左全部 + 右独有的(无需 Set,O(K) in 查找)
*/
const mergedKeys = (left: Record<string, unknown>, right: Record<string, unknown>): string[] => {
const result: string[] = Object.keys(left);
for (const k of Object.keys(right)) {
if (!(k in left)) result.push(k);
}
return result;
};
/**
* 比较两个 JSON 值的差异(迭代版,显式栈替代递归)
*/ */
export const diffJson = (left: unknown, right: unknown): DiffResult => { export const diffJson = (left: unknown, right: unknown): DiffResult => {
const diffPaths: string[] = []; const diffPaths: string[] = [];
const root = diffNode(left, right, '', ROOT_PATH, diffPaths);
const rootFrame: StackFrame = {
left,
right,
key: '',
path: ROOT_PATH,
childCount: 0,
assembled: false,
leftObj: isObject(left),
rightObj: isObject(right),
leftArr: isArray(left),
rightArr: isArray(right),
leftIsContainer: isObject(left) || isArray(left),
rightIsContainer: isObject(right) || isArray(right),
};
const stack: StackFrame[] = [rootFrame];
const resultStack: DiffNode[] = [];
while (stack.length > 0) {
const frame = stack.pop()!;
// ---- 组装阶段:从 resultStack 弹出子节点 ----
if (frame.assembled) {
const { childCount } = frame;
const children: DiffNode[] = new Array(childCount);
// 子节点按正序压入 resultStack,弹出时逆序取
for (let i = childCount - 1; i >= 0; i--) {
children[i] = resultStack.pop()!;
}
const hasDiffInChildren = children.some((c) => c.type !== 'unchanged' || c.hasDiffInChildren);
const type: DiffNode['type'] = hasDiffInChildren ? 'modified' : 'unchanged';
const node: DiffNode = {
key: frame.key,
type,
oldValue: frame.left === SENTINEL ? undefined : frame.left,
newValue: frame.right === SENTINEL ? undefined : frame.right,
children,
path: frame.path,
isLeaf: false,
hasDiffInChildren,
};
resultStack.push(node);
continue;
}
const { left: l, right: r } = frame;
// ---- 一侧缺失 ----
if (l === SENTINEL && r !== SENTINEL) {
diffPaths.push(frame.path);
resultStack.push(createLeafNode(frame.key, frame.path, 'added', undefined, r));
continue;
}
if (r === SENTINEL && l !== SENTINEL) {
diffPaths.push(frame.path);
resultStack.push(createLeafNode(frame.key, frame.path, 'removed', l, undefined));
continue;
}
// ---- 双侧对象 ----
if (frame.leftObj && frame.rightObj) {
const keys = mergedKeys(l as Record<string, unknown>, r as Record<string, unknown>);
// 压入组装帧
stack.push({ ...frame, childCount: keys.length, assembled: true });
// 逆序压入子帧,保证正序处理
for (let i = keys.length - 1; i >= 0; i--) {
const k = keys[i];
const childPath = buildPath(frame.path, k, false);
const leftVal: MaybeMissing =
k in (l as Record<string, unknown>) ? (l as Record<string, unknown>)[k] : SENTINEL;
const rightVal: MaybeMissing =
k in (r as Record<string, unknown>) ? (r as Record<string, unknown>)[k] : SENTINEL;
stack.push({
left: leftVal,
right: rightVal,
key: k,
path: childPath,
childCount: 0,
assembled: false,
leftObj: isObject(leftVal),
rightObj: isObject(rightVal),
leftArr: isArray(leftVal),
rightArr: isArray(rightVal),
leftIsContainer: isObject(leftVal) || isArray(leftVal),
rightIsContainer: isObject(rightVal) || isArray(rightVal),
});
}
continue;
}
// ---- 双侧数组 ----
if (frame.leftArr && frame.rightArr) {
const leftArr = l as unknown[];
const rightArr = r as unknown[];
const len = Math.max(leftArr.length, rightArr.length);
stack.push({ ...frame, childCount: len, assembled: true });
for (let i = len - 1; i >= 0; i--) {
const k = String(i);
const childPath = buildPath(frame.path, k, true);
const leftVal: MaybeMissing = i < leftArr.length ? leftArr[i] : SENTINEL;
const rightVal: MaybeMissing = i < rightArr.length ? rightArr[i] : SENTINEL;
stack.push({
left: leftVal,
right: rightVal,
key: k,
path: childPath,
childCount: 0,
assembled: false,
leftObj: isObject(leftVal),
rightObj: isObject(rightVal),
leftArr: isArray(leftVal),
rightArr: isArray(rightVal),
leftIsContainer: isObject(leftVal) || isArray(leftVal),
rightIsContainer: isObject(rightVal) || isArray(rightVal),
});
}
continue;
}
// ---- 原始值比较 ----
if (!frame.leftIsContainer && !frame.rightIsContainer) {
const primitiveResult = classifyPrimitive(l, r, frame.key, frame.path);
if (primitiveResult) {
resultStack.push(primitiveResult);
continue;
}
}
// 类型不同或容器 vs 原始值 → modified
diffPaths.push(frame.path);
resultStack.push({
key: frame.key,
type: 'modified',
oldValue: l,
newValue: r,
path: frame.path,
isLeaf: !frame.leftIsContainer && !frame.rightIsContainer,
hasDiffInChildren: false,
});
}
const root = resultStack[resultStack.length - 1];
return { return {
root, root,
diffPaths, diffPaths,
-1
View File
@@ -11,7 +11,6 @@ export default {
'./src/components/ErrorBoundary.tsx', './src/components/ErrorBoundary.tsx',
'./src/components/ErrorFallback.tsx', './src/components/ErrorFallback.tsx',
'./src/components/PageErrorBoundary.tsx', './src/components/PageErrorBoundary.tsx',
'./src/components/PageSkeleton.tsx',
'./src/components/ui/button.tsx', './src/components/ui/button.tsx',
'./src/components/ui/input.tsx', './src/components/ui/input.tsx',
'./src/components/ui/sonner.tsx', './src/components/ui/sonner.tsx',