Compare commits

..

4 Commits

Author SHA1 Message Date
rsgltzyd 06c2a222ab 重构导航逻辑,去除dashboard页面相关功能,增加侧边栏导航功能 2026-07-05 22:34:12 +08:00
rsgltzyd 1af3b25af8 Merge branch 'develop' 2026-07-05 21:39:32 +08:00
rsgltzyd 550f8f82c7 Merge branch 'develop' 2026-06-30 23:26:27 +08:00
LingandRX 36b6bfd20d Develop (#74)
* feat: 生成成功改为 toast 提示
* refactor: 数据预览改为显示示例数据,简化组件逻辑
* fix: 非必填字段预览显示 null
* fix: 修复空值率与必填状态的逻辑
* fix: 切换为非必填时默认空值率 100%
* feat: 字段编辑弹窗添加「完成」按钮 去除关闭按钮,添加取消按钮
* refactor: 删除未使用的 defaultNullRate 功能
* feat: 优化规则管理功能
* fix: 更新 features 测试断言以匹配新增的 testDataGenerator
* refactor: 将 formatFileSize 重命名为 formatBytes 并移至通用工具模块
* refactor: 使用 Label 组件替换原生 label 元素,并在 DecodeResultPaper 中引入 Input 组件
* refactor: 规范化页面组件目录结构
* refactor(JsonTools): 规范化页面组件目录结构
* refactor(StorageCleaner): 规范化页面组件目录结构
* refactor(Timestamp): 规范化页面组件目录结构
* refactor(i18n): 移除 chrome.i18n 国际化,统一使用中文硬编码
* refactor(AppRoot): 移除 RouterProvider 组件,直接渲染子组件
* fix(RouterProvider): 将 goBack 重命名为 goHome,修复跨窗同步 merge 不一致
* fix(ThemeModeProvider): 修复主题快照同步与首屏闪烁问题
* refactor: 将 UI 文案改为中文并优化相关逻辑
* refactor: 清理代码注释并优化组件结构
* feat(Dashboard): 重构仪表板功能组件和逻辑
* refactor: 更新功能键名称并移除 README 文件
* refactor: 重构 TopBar 组件并更新项目结构
* feat(TopBar): 添加搜索功能组件并优化结构
* refactor: 统一使用 Button 组件替换原有 button 元素
* feat: 添加 EmptyPlaceholder 组件并更新相关页面
* feat(TextStatistics): 引入 StatCard 组件以优化统计信息展示
* feat(Timestamp): 重构时间戳转换功能,新增 ConverterForm 组件
* feat(Jwt): 重构 JWT 组件,新增常量和结果视图
* refactor(RightClickRestorer): 用状态配置表简化页面 UI 结构
* fix(business): 修复 skewedRandom 函数中的数学计算错误
* refactor(ImageUploader): 移除预览 URL 相关逻辑并简化粘贴事件处理
* feat(TestDataGenerator): 更新规则编辑提示和警告显示逻辑
* refactor(CopyButton.test): 移除冗余测试用例
* refactor(RouterProvider, chromeStorage, useContextMenuData): 更新存储获取逻辑以移除默认值参数
* refactor(代码重复): 抽取共享工具函数与 UI 组件,消除多处重复实现
* fix(RouterProvider): 修复初始加载状态逻辑,确保在加载前不覆盖 chrome.storage
* feat(TopBar): 添加搜索框快捷键提示功能及相关测试
* refactor(StorageCleaner): 移动 isRestrictedUrl 函数到独立模块并更新相关引用
* fix(StorageCleaner): 修复 IndexedDB 清理竞态、部分成功计数与刷新后状态同步
* fix: 修复路由初始化竞态、存储状态静默覆盖与存储清理误删
* refactor: 统一中文文案并简化组件结构,提升代码可读性
* refactor: 更新 Worker 消息类型以支持生成任务 ID
* fix: 修复 ruleStorage 写入失败处理与 CopyButton 成功态样式
2026-06-27 17:58:59 +08:00
23 changed files with 296 additions and 281 deletions
+3 -2
View File
@@ -669,7 +669,7 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
### 9.1 功能元数据
功能名称与描述在 `config/features.tsx``FEATURES` 数组中定义:
功能名称与描述在 `config/featureMeta.ts``FEATURES` 数组中定义:
```typescript
{
@@ -677,10 +677,11 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
label: '时间戳转换',
description: '日期与时间戳互转',
defaultVisible: true,
component: TimestampPage,
}
```
页面组件通过 `config/pageLoaders/` 按需加载,不在 `FEATURES` 中引用。
Dashboard 卡片、TopBar 搜索等功能从此处读取 `label` / `description`
### 9.2 页面与组件文案
+7 -7
View File
@@ -382,14 +382,14 @@ function loadRule(ruleId: string): void {
使用 `localStorage`,键名 `testDataGenerator_rules`。API 为**命名导出函数**(见 `src/utils/ruleStorage.ts`):
| 函数 | 说明 |
| ---- | ---- |
| `getAll()` / `getById()` / `getByName()` | 读取 |
| 函数 | 说明 |
| ------------------------------------------------------ | ---------------------------------- |
| `getAll()` / `getById()` / `getByName()` | 读取 |
| `save()` / `update()` / `deleteRule()` / `duplicate()` | 写入;失败时返回 `null``false` |
| `recordUse()` | 递增 `useCount`、更新 `lastUsedAt` |
| `search()` / `getRecent()` | 搜索与最近使用 |
| `exportRules()` / `importRules()` | 导入导出 JSON 数组 |
| `clear()` | 清空全部规则 |
| `recordUse()` | 递增 `useCount`、更新 `lastUsedAt` |
| `search()` / `getRecent()` | 搜索与最近使用 |
| `exportRules()` / `importRules()` | 导入导出 JSON 数组 |
| `clear()` | 清空全部规则 |
写入失败(如 `QuotaExceededError`)时,内部 `setAll()` 返回 `false``save`/`update` 返回 `null``deleteRule` 返回 `false`,并在控制台输出 `[ruleStorage] 保存规则失败`。调用方须检查返回值,避免误报成功。
@@ -1505,9 +1505,7 @@ export class DataExporter {
```typescript
// src/types/testDataGenerator.ts
type WorkerRequestMessage =
| { type: 'start'; payload: WorkerStartPayload }
| { type: 'cancel' };
type WorkerRequestMessage = { type: 'start'; payload: WorkerStartPayload } | { type: 'cancel' };
type WorkerResponseMessage =
| { type: 'progress'; generationId: number; payload: GenerateProgress }
+41
View File
@@ -0,0 +1,41 @@
/**
* 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 -1
View File
@@ -6,7 +6,7 @@
| 组件 | 用途 |
| ----------------------- | ------------------------------------------------------------------------------------------------------ |
| `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界 |
| `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界和骨架屏 |
| `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 |
| `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 |
| `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 |
@@ -17,6 +17,7 @@
| `GlobalSnackbar.tsx` | 全局消息提示组件 + Context Provider,支持受控/Hook/全局单例三种使用方式 |
| `ErrorBoundary.tsx` | 全局错误边界(类组件),捕获子组件树 JS 错误并展示友好错误页面 |
| `PageErrorBoundary.tsx` | 页面级错误边界,适配 shadcn 暗黑模式,支持 `resetKey` 自动恢复 |
| `PageSkeleton.tsx` | 页面骨架屏,提供 `dashboard``tool` 两种变体,用于 Suspense fallback |
## 使用约定
+2 -1
View File
@@ -4,6 +4,7 @@ import { useRouter } from '@/providers/RouterProvider';
import type { PageType } from '@/types/storage';
import { type ComponentType, useEffect, useState } from 'react';
import PageErrorBoundary from '@/components/PageErrorBoundary';
import PageSkeleton from '@/components/PageSkeleton';
import { cn } from '@/lib/utils';
import { AlertTriangle } from 'lucide-react';
@@ -29,7 +30,7 @@ function LoadedPage({ pageKey }: { pageKey: PageType }) {
}, [pageKey]);
if (!Page) {
return <div className="flex-1" aria-hidden="true" />;
return <PageSkeleton />;
}
return <Page />;
+5 -4
View File
@@ -15,6 +15,7 @@ export interface SwitchButtonGroupProps<T extends string | number = string> exte
options: SwitchOption<T>[];
onChange: (value: T) => void;
size?: 'small' | 'medium' | 'large';
buttonClassName?: string;
}
const SIZE_CLASSES = {
@@ -23,10 +24,8 @@ const SIZE_CLASSES = {
large: 'text-base h-11 px-4 py-2 rounded-lg',
} as const;
const SELECTED_CLASSES =
'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';
const SELECTED_CLASSES = 'bg-background text-foreground shadow-sm font-semibold fade-in-zoom-95';
const UNSELECTED_CLASSES = 'hover:bg-background/50 hover:text-foreground/80';
export default function SwitchButtonGroup<T extends string | number = string>({
value,
@@ -34,6 +33,7 @@ export default function SwitchButtonGroup<T extends string | number = string>({
onChange,
size = 'medium',
className,
buttonClassName,
...props
}: SwitchButtonGroupProps<T>) {
return (
@@ -54,6 +54,7 @@ export default function SwitchButtonGroup<T extends string | number = string>({
'flex-1 transition-all',
SIZE_CLASSES[size],
value === option.value ? SELECTED_CLASSES : UNSELECTED_CLASSES,
buttonClassName,
)}
>
{option.label}
@@ -0,0 +1,32 @@
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(
},
);
interface BadgeProps
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge };
export { Badge, badgeVariants };
+1 -1
View File
@@ -46,4 +46,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
);
Button.displayName = 'Button';
export { Button };
export { Button, buttonVariants };
+1 -1
View File
@@ -5,7 +5,7 @@ import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
const Checkbox = React.forwardRef<
React.ComponentRef<typeof CheckboxPrimitive.Root>,
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
+4 -4
View File
@@ -12,7 +12,7 @@ const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Overlay>,
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
@@ -33,7 +33,7 @@ interface DialogContentProps extends React.ComponentPropsWithoutRef<
}
const DialogContent = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Content>,
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, showCloseButton = true, ...props }, ref) => (
<DialogPortal>
@@ -72,7 +72,7 @@ const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivEleme
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Title>,
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
@@ -84,7 +84,7 @@ const DialogTitle = React.forwardRef<
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Description>,
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
+1 -1
View File
@@ -9,7 +9,7 @@ const labelVariants = cva(
);
const Label = React.forwardRef<
React.ComponentRef<typeof LabelPrimitive.Root>,
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
+30 -7
View File
@@ -10,7 +10,7 @@ const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Trigger>,
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
@@ -30,7 +30,7 @@ const SelectTrigger = React.forwardRef<
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.ScrollUpButton>,
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
@@ -44,7 +44,7 @@ const SelectScrollUpButton = React.forwardRef<
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.ScrollDownButton>,
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
@@ -58,7 +58,7 @@ const SelectScrollDownButton = React.forwardRef<
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Content>,
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
@@ -90,7 +90,7 @@ const SelectContent = React.forwardRef<
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Label>,
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
@@ -102,7 +102,7 @@ const SelectLabel = React.forwardRef<
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Item>,
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
@@ -124,4 +124,27 @@ const SelectItem = React.forwardRef<
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem };
const SelectSeparator = React.forwardRef<
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';
const Switch = React.forwardRef<
React.ComponentRef<typeof SwitchPrimitives.Root>,
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
+1 -2
View File
@@ -1,6 +1,5 @@
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
return clsx(inputs);
}
@@ -84,11 +84,7 @@ export default function GeneratorConfig({ generator, params, onChange }: Generat
</SelectTrigger>
<SelectContent>
{param.options?.map((option) => (
<SelectItem
key={String(option.value)}
value={String(option.value)}
className="cursor-pointer"
>
<SelectItem key={String(option.value)} value={String(option.value)}>
{option.label}
</SelectItem>
))}
@@ -41,7 +41,10 @@ export default function ConverterForm({
placeholder={INPUT_PLACEHOLDERS[mode]}
value={input}
onChange={(e) => setInput(e.target.value)}
className={cn('h-10', error && 'border-destructive')}
className={cn(
'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>}
@@ -57,13 +60,16 @@ export default function ConverterForm({
/>
<Select value={zone} onValueChange={(v: string) => setZone(v as ZoneType)}>
<SelectTrigger>
<SelectTrigger className="flex-1 font-mono font-semibold h-9 shadow-sm bg-background">
<SelectValue placeholder="选择时区" />
</SelectTrigger>
<SelectContent className="max-h-64">
<SelectContent className="max-h-64 font-mono">
{ZONES.map((z) => (
<SelectItem key={z} value={z} className="cursor-pointer">
<SelectItem
key={z}
value={z}
className="text-xs font-semibold focus:bg-accent cursor-pointer"
>
{z}
</SelectItem>
))}
+11 -8
View File
@@ -1,5 +1,4 @@
import type { HTMLAttributes } from 'react';
import { useEffect, useState } from 'react';
import React, { useEffect, useState } from 'react';
import { Clock } from 'lucide-react';
import { toast } from 'sonner';
import { CopyButton } from '@/components/CopyButton';
@@ -8,7 +7,7 @@ import { msToUnit } from '../constants';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
interface LiveClockProps extends HTMLAttributes<HTMLDivElement> {
interface LiveClockProps extends React.HTMLAttributes<HTMLDivElement> {
unit: UnitType;
onUseNow: (val: number) => void;
}
@@ -29,14 +28,18 @@ export default function LiveClock({ unit, onUseNow, className, ...props }: LiveC
return (
<div
className={cn(
'flex items-center gap-3 px-3 h-10 rounded-lg font-bold text-[12px] border px-[20px]',
'flex items-center gap-3 px-3 h-10 rounded-lg border border-border/80 bg-secondary/50',
className,
)}
{...props}
>
<span></span>
<span className="text-muted-foreground font-bold text-[10px] uppercase tracking-wider whitespace-nowrap shrink-0 selection:bg-transparent select-none">
</span>
<span className="flex-1 text-sm ">{text}</span>
<span className="flex-1 font-mono font-bold text-foreground text-sm tracking-tight leading-none truncate tabular-nums">
{text}
</span>
<Button
type="button"
@@ -47,12 +50,12 @@ export default function LiveClock({ unit, onUseNow, className, ...props }: LiveC
title="填充到下方"
variant="ghost"
size="icon"
className="h-7 w-7"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
>
<Clock className="w-3.5 h-3.5" />
</Button>
<CopyButton text={text} tooltip="复制时间戳" className="h-7 w-7" />
<CopyButton text={text} tooltip="复制时间戳" className="h-7 w-7 rounded-md border" />
</div>
);
}
@@ -34,15 +34,16 @@ export default function ResultView({
</span>
<div className="bg-card border p-4 rounded-lg flex items-center gap-3 justify-between">
<span className="break-all text-lg select-all flex-1">{result}</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">
<span className="font-mono font-extrabold text-foreground break-all text-xl sm:text-2xl tracking-tight leading-tight select-all tabular-nums">
{result}
</span>
<CopyButton
text={result}
tooltip="复制结果"
variant="ghost"
size="icon"
className="h-7 w-7"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
/>
</div>
</div>
+8 -8
View File
@@ -7,8 +7,8 @@
| 文件 | 用途 |
| ------------------------ | --------------------------------------------------------------------------------------------------- |
| `chromeStorage.ts` | Chrome Storage API 封装:类型安全的 `StorageUtils` 类,提供 `get/set/remove` 方法 |
| `syncSnapshot.ts` | 通用 `localStorage` 快照读取(`snapshot/{key}`),用于 Router 与 `useStorageState` 首屏防闪烁 |
| `themeSnapshot.ts` | 主题专用快照读写与 `document.documentElement` class 切换 |
| `syncSnapshot.ts` | 通用 `localStorage` 快照读取(`snapshot/{key}`),用于 Router 与 `useStorageState` 首屏防闪烁 |
| `themeSnapshot.ts` | 主题专用快照读写与 `document.documentElement` class 切换 |
| `restrictedUrls.ts` | 受限 URL 检测(`chrome://``about:` 等),供 Storage Cleaner 等模块复用 |
| `chromeTabs.ts` | Chrome Tabs API 封装:获取活动标签页、获取域名、在新标签页打开扩展页面 |
| `clipboard.ts` | 剪贴板操作:`copyTextToClipboard`(文本)、`copyImageToClipboard`(图片) |
@@ -42,12 +42,12 @@
写入经内部 `setAll()` 完成;`localStorage.setItem` 抛错(如配额超限)时返回 `false`,并 `console.error`**不会部分提交**
| 方法 | 写入失败返回值 | 常见失败原因 |
| ---- | -------------- | ------------ |
| `save()` | `null` | 达上限、规则不存在(更新时)、`setItem` 异常 |
| `update()` | `null` | 规则不存在、`setItem` 异常 |
| `deleteRule()` | `false` | 规则不存在、`setItem` 异常 |
| `duplicate()` | 仍可能返回对象但数据未持久化 | 见源码:`duplicate` 未检查 `setAll` 返回值(已知缺口) |
| 方法 | 写入失败返回值 | 常见失败原因 |
| -------------- | ---------------------------- | ------------------------------------------------------ |
| `save()` | `null` | 达上限、规则不存在(更新时)、`setItem` 异常 |
| `update()` | `null` | 规则不存在、`setItem` 异常 |
| `deleteRule()` | `false` | 规则不存在、`setItem` 异常 |
| `duplicate()` | 仍可能返回对象但数据未持久化 | 见源码:`duplicate` 未检查 `setAll` 返回值(已知缺口) |
调用方应检查返回值后再展示成功 Toast。页面层参考 `FieldList.tsx``save`/`update` 返回非空才提示「规则已保存/已更新」。
+125 -214
View File
@@ -19,6 +19,7 @@ const buildPath = (parent: string, key: string, isArrayChild: boolean): string =
}
const needsEscaping = key.includes('.') || key.includes('[') || key.includes(' ');
const formattedKey = needsEscaping ? `["${key}"]` : `.${key}`;
return parent === ROOT_PATH ? `${ROOT_PATH}${formattedKey}` : `${parent}${formattedKey}`;
};
@@ -29,239 +30,149 @@ const primitiveEqual = (a: unknown, b: unknown): boolean => {
return a === b;
};
// ---------- 迭代遍历框架 ----------
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 = (
const diffNode = (
left: MaybeMissing,
right: MaybeMissing,
key: string,
path: string,
): DiffNode | null => {
if (left === null || right === null) {
if (left === null && right === null) {
return {
key,
type: 'unchanged',
oldValue: left,
newValue: right,
path,
isLeaf: true,
hasDiffInChildren: false,
};
}
return null;
}
if (typeof left === typeof right && primitiveEqual(left, right)) {
diffPaths: string[],
): DiffNode => {
if (left === SENTINEL && right !== SENTINEL) {
diffPaths.push(path);
return {
key,
type: 'unchanged',
oldValue: left,
type: 'added',
oldValue: undefined,
newValue: right,
path,
isLeaf: true,
isLeaf: !isObject(right) && !isArray(right),
hasDiffInChildren: false,
};
}
return null;
};
/**
* 合并对象 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);
if (right === SENTINEL && left !== SENTINEL) {
diffPaths.push(path);
return {
key,
type: 'removed',
oldValue: left,
newValue: undefined,
path,
isLeaf: !isObject(left) && !isArray(left),
hasDiffInChildren: false,
};
}
return result;
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) {
return {
key,
type: 'unchanged',
oldValue: left,
newValue: right,
path,
isLeaf: true,
hasDiffInChildren: false,
};
}
} else if (typeof left === typeof right) {
if (primitiveEqual(left, right)) {
return {
key,
type: 'unchanged',
oldValue: left,
newValue: right,
path,
isLeaf: true,
hasDiffInChildren: false,
};
}
}
}
diffPaths.push(path);
return {
key,
type: 'modified',
oldValue: left,
newValue: right,
path,
isLeaf: !leftIsContainer && !rightIsContainer,
hasDiffInChildren: false,
};
};
/**
* 比较两个 JSON 值的差异(迭代版,显式栈替代递归)
* 比较两个 JSON 值的差异
*/
export const diffJson = (left: unknown, right: unknown): DiffResult => {
const diffPaths: string[] = [];
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];
const root = diffNode(left, right, '', ROOT_PATH, diffPaths);
return {
root,
diffPaths,
+1
View File
@@ -11,6 +11,7 @@ export default {
'./src/components/ErrorBoundary.tsx',
'./src/components/ErrorFallback.tsx',
'./src/components/PageErrorBoundary.tsx',
'./src/components/PageSkeleton.tsx',
'./src/components/ui/button.tsx',
'./src/components/ui/input.tsx',
'./src/components/ui/sonner.tsx',