feat: Tailwind CSS/shadcn/ui 迁移 & 右键菜单功能 (#42)
* feat: 添加 contextMenus 权限和消息类型定义
* feat: 实现右键菜单注册与点击分流逻辑
- 新增 utils/contextMenu.ts 封装菜单配置和解析函数
- 在 background.ts 监听 onInstalled 初始化菜单
- 实现 contextMenus.onClicked 点击事件处理
- 分流逻辑:优先发送到侧边栏,否则打开 options 页面
- 添加 contextMenu 单元测试(15个测试用例)
- 更新 vitest.setup.ts 添加 contextMenus mock
* feat: 实现 Content Script 原位轻量提示 UI
- 新增 uiPopover.ts 实现原位弹窗组件(深色主题、自动定位、自动隐藏)
- 新增 contextMenuHandler.ts 处理右键菜单消息
- 时间戳转换:在点击位置显示转换结果
- 文本统计:显示字符/单词/行数/字节统计
- 更新 messageHandler.ts 挂载右键菜单消息监听
* feat: 实现 React 页面层右键菜单数据联动
- 新增 useContextMenuData Hook 处理右键菜单数据传递
- 重构 Jwt/Base64Converter/TextStatistics/QrCode 页面接收右键数据
- RouterProvider 支持从 URL 参数解析右键菜单数据
- 添加 contextMenu/pendingData 存储键到 StorageSchema
- 添加 useContextMenuData 单元测试(12个测试用例)
* test: 添加 background 单元测试与边界情况处理
- 新增 entrypoints/__tests__/background.test.ts (12个测试用例)
- 超长文本截断限制 (>10000字符)
- Base64 内联图片拦截并返回错误提示
- 更新 parseContextMenuClick 返回 ParseResult 格式
- 更新测试匹配新的返回格式
- lint/typecheck/test 全部通过 (579个测试)
* fix: 修复右键菜单跳转到错误页面的问题
- 将 options 页面路径从 '/entrypoints/options/index.html' 修正为 '/options.html'
- WXT 构建后 entrypoints/options/index.html 会输出为根目录的 options.html
* fix: 修复右键菜单跳转目标为 popup 页面
- 将 fallback 页面从 options.html 改为 popup.html
- popup 页面使用 RouterProvider,可以正确处理 URL 参数并跳转到对应功能页面
- options 页面是独立设置页,不支持 URL 参数路由
* fix: 使用 openPopup() 替代 tabs.create() 打开弹窗
- background.ts: 使用 browser.action.openPopup() 打开 popup 弹窗
- 先保存数据到 storage,然后打开 popup
- RouterProvider.tsx: 初始化时检查 storage 中的 pendingData 并跳转到对应页面
- 移除之前错误的 tabs.create() 方式
* fix: 修复右键菜单数据未传递到目标页面的问题
- RouterProvider 不再提前清除 pendingData
- 让目标页面的 useContextMenuData 来消费和清除数据
- 这样确保 TextStatistics 等页面能正确接收选中的文本
* fix: 修复 popup 已打开时右键菜单不生效的问题
- 在 RouterProvider 中添加对 contextMenu/pendingData 的 storage 变化监听
- 当 pendingData 变化时,自动跳转到对应功能页面
- 解决了 openPopup() 只聚焦已有窗口而不触发重新挂载的问题
* feat: 支持右键菜单图片二维码识别
- 在 qrCodeParser.ts 中添加 parseQrCodeFromUrl 函数,支持从图片 URL 解析二维码
- 在 QrCodeToUrlSection 中使用 useContextMenuData 接收右键菜单传递的图片 URL
- 自动下载图片并解析二维码,显示解析结果
* refactor: 暂时移除图片二维码识别功能
- 删除 qrCode-image 右键菜单配置
- 删除 parseQrCodeFromUrl 函数
- 删除 QrCodeToUrlSection 中的 useContextMenuData 相关代码
- 更新相关测试用例
* feat: 支持右键菜单时间戳转换
- 在 useTimestampConverter 中添加 useContextMenuData hook
- 智能识别输入是时间戳还是日期时间字符串
- 自动切换到对应模式并执行转换
- 时间戳自动识别秒/毫秒单位
* fix: 修复右键菜单功能的多个逻辑漏洞
1. 修复时区硬编码问题 - 使用用户选择的时区而非固定 Asia/Shanghai
2. 修复 openPopup() 失败后数据残留 - 失败时清除 storage 中的待处理数据
3. 统一数据过期时间常量 - 导出 CONTEXT_MENU_DATA_EXPIRY_MS 并统一使用
4. 修复 featureKey 类型断言不安全 - 使用映射表处理非常规菜单 ID
* refactor(qrcode): 提取独立组件并添加单元测试
- 创建 pages/QrCode/types.ts 定义状态类型接口
- 提取 QrCodePreview 组件用于二维码预览和操作
- 提取 ImageUploader 组件封装图片上传、拖拽、粘贴逻辑
- 重构 UrlToQrCodeSection 状态提升到父组件
- 重构 QrCodeToUrlSection 通过回调传递解析结果
- 更新主页面 index.tsx 集中管理所有状态
- 为 QrCodePreview 和 ImageUploader 添加单元测试 (23 个用例)
* refactor(qrcode): 引入通用组件并重构双栏布局
- 引入 SwitchButtonGroup 用于模式切换
- 引入 TextInputArea 用于文本输入和结果展示
- 使用 MUI Grid 构建响应式双栏布局
- 实现 generate/parse 模式下的左右面板内容切换
- 修复 iconColor 颜色格式错误,使用 qrCodePageStyles.primaryColor
* refactor(qrcode): 国际化补充、质量保障与错误处理优化
- 补充 i18n 翻译键(generateMode, parseMode, pasteHint 等)
- 创建 useDebounce Hook 实现输入防抖 (200ms)
- 使用 useRef 解决 useEffect 无限循环问题
- 编写 pages/QrCode 单元测试 (7 个用例)
- 优化右键菜单错误处理,改进用户提示
- 运行 603 个测试全部通过
* refactor(qrcode): 组件化重构,采用 Context + Hook 模式
- 创建 QrCodeContext 和 QrCodeProvider 管理共享状态
- 提取 useQrCode Hook 封装所有状态和业务逻辑
- 创建 GeneratePanel 组件处理二维码生成模式
- 创建 ParsePanel 组件处理二维码解析模式
- 简化 index.tsx 为容器组件 (340行 → 47行)
- 删除未使用的旧组件文件 (QrCodeToUrlSection, UrlToQrCodeSection)
- 清理 types.ts 中未使用的类型定义
- 603 个测试全部通过
* fix(qrcode): 固定二维码预览图片尺寸,避免布局抖动
- 设置 QR_PREVIEW_IMAGE 固定尺寸 250x250
- 与 QRious 生成的二维码大小保持一致
- 解决输入内容变化时预览窗口大小跳动问题
* fix(qrcode): 修复切换 tab 后二维码图片失效问题
- 移除 ImageUploader 组件卸载时的预览 URL 释放逻辑
- 在 useQrCode hook 中统一管理预览 URL 生命周期
- 创建新预览 URL 前释放旧的,避免内存泄漏
* fix(qrcode): 固定图片上传区域高度,避免布局抖动
- 将 DROPZONE 的 minHeight: 200 改为 height: 250
- 与二维码预览图片高度保持一致
- 解决上传图片时 div 高度变化问题
* refactor(qrCode): 优化二维码解析功能
- 将'二维码转 URL'改为'二维码转文本'
- 将解析结果的文本预览框的 placeholder 置为空
- 去除手动解析二维码功能,只保留自动解析
* fix(pageHeader): 使用 MUI 主题色替代硬编码颜色,支持暗色模式
* feat(pageHeader): popup 模式下隐藏 PageHeader 组件
* fix(i18n): 统一使用 useLazyTranslation 避免翻译 key 闪烁
* perf: 配置 manualChunks 拆分 vendor chunk,优化打包体积
- 使用 Vite 插件 manualChunksForHtmlOnly 仅对 HTML 多入口构建生效
- 跳过 background/content-script 的 IIFE 构建(不支持 manualChunks)
- 拆分 vendor-react (193KB)、vendor-mui (326KB)、vendor-i18n (55KB)
- 按需加载 vendor-qr (78KB)、vendor-dnd (45KB)、vendor-markdown (41KB)
- PageErrorBoundary chunk 从 454KB 降至 36KB
* chore: upgrade wxt to v0.20.26 and @wxt-dev/module-react to v1.2.2
* chore: upgrade low-risk dependencies
- react: 19.2.3 → 19.2.6
- react-dom: 19.2.3 → 19.2.6
- dayjs: 1.11.19 → 1.11.20
- marked: 18.0.3 → 18.0.4
- prettier: 3.8.1 → 3.8.3
- terser: 5.46.0 → 5.47.1
- i18next: 26.0.8 → 26.2.0
- react-i18next: 17.0.6 → 17.0.8
- globals: 17.2.0 → 17.6.0
- eslint-plugin-react-hooks: 7.0.1 → 7.1.1
- @typescript-eslint/*: 8.54.0 → 8.59.4
- typescript-eslint: 8.54.0 → 8.59.4
- @testing-library/jest-dom: 6.6.0 → 6.9.1
- @testing-library/react: 16.0.0 → 16.3.2
- @testing-library/user-event: 14.5.2 → 14.6.1
- @testing-library/dom: added as peer dependency
- @types/react: 19.2.7 → 19.2.15
- @types/chrome: 0.1.36 → 0.1.42
- @types/webextension-polyfill: 0.12.4 → 0.12.5
* chore: upgrade medium-risk dependencies
- lint-staged: 16.2.7 → 17.0.5
- jsdom: 25.0.0 → 29.1.1
- @vitejs/plugin-react: 4.3.4 → 6.0.2
- vitest: 2.0.0 → 4.1.7
- @vitest/coverage-v8: upgraded to match vitest
- @webext-core/messaging: 2.3.0 → 3.0.1
- eslint: 9.39.2 → 10.4.0
- @eslint/js: added as new dependency
- @types/marked: removed (marked now provides its own types)
Fixes:
- Fix ref update during render in useQrCode.ts
- Fix ref update during render in useStorageCleaner.ts
- Add error cause in jwt.ts decode function
- Add type assertion for mock functions in htmlToMarkdown.test.ts
* chore(deps): 降级 eslint 版本并移除 @eslint/js
* docs: 精简 AGENTS.md,聚焦高信号信息
* test: 修复测试中的 act() 警告和 clipboard mock 问题
- TextInputArea: 使用 userEvent 替代 fireEvent,用 vi.spyOn 替代 Object.assign mock clipboard
- ImageMode/FileMode: 添加 waitForStorageReady() 等待 useStorageState 异步初始化
* perf: 优化首屏加载,快照有效时跳过骨架屏
- isLoaded 初始值根据 localStorage 快照是否存在决定
- 后续访问直接渲染真实 DOM,无需等待 chrome.storage 异步加载
- loadInitialData 仍在后台静默执行确保数据同步
* 引入 Tailwind CSS 和 shadcn/ui
* 替换 Timestamp 页面图标为 lucide-react 的 Clock 图标
* 用 Tailwind CSS 重写 Timestamp 页面的 MUI 基础排版组件
* 用 Tailwind CSS 重构 ResultView 和 LiveClock 组件
* 用 Tailwind CSS 重写 Dashboard/index.tsx 和 ToolCard.tsx
* 用 Tailwind CSS 重写 TextStatistics 页面
* 用 Tailwind CSS 重写 Base64Converter 页面
* 用 Tailwind CSS 重写 QrCode 页面及相关组件
* 用 Tailwind CSS 重写 Jwt 页面
* 用 Tailwind CSS 重写 StorageCleaner 页面,创建 shadcn/ui Dialog 组件
* 用 Tailwind CSS 重写 JsonTools 页面
* 用 Tailwind CSS 重构所有共享组件
* 修复 TypeScript 类型错误:将 MUI sx 语法改成标准 CSS 属性
* 重写基础骨架组件:用纯 Tailwind CSS 替换 MUI Box 组件
* 重写所有页面和组件:用纯 Tailwind CSS 替换 MUI 组件和图标
* 移除 MUI 依赖,简化配置文件,重写 ThemeModeProvider
* 移除 wxt.config.ts 中残留的 MUI chunk 配置
* 为 Dialog 组件添加暗黑模式背景色支持
* fix: 修复暗黑模式样式兼容性
- 在 tailwind.config.js 中启用 darkMode: 'class' 并扩展语义化颜色变量
- 将全项目硬编码颜色(bg-white、text-gray-*、border-gray-* 等)替换为语义化类名
- 修复 popup/index.html 硬编码浅色背景色
- 同步更新相关单元测试中的类名断言
* fix: 修复输入框和按钮在暗色模式下的样式问题
- 为 :root 和 .dark 添加 color-scheme,使浏览器表单控件默认样式适配暗色模式
- 将 bg-primary 搭配 text-white 的按钮改为 text-primary-foreground
- 替换残留的 hover:bg-blue-700、text-blue-500、bg-gray-200 等硬编码颜色
- 同步更新 TextInputArea 单元测试
* fix: 增强 SwitchButtonGroup 和立即转换按钮的视觉层级
- SwitchButtonGroup 选中按钮阴影从 shadow-sm 升级到 shadow-md
- 同步更新单元测试中断言
- Timestamp 立即转换按钮添加 shadow-md 增强边界感
* style: 隐藏所有窗口的滚动条
- 在全局 CSS 中为 html 添加 scrollbar-width: none(Firefox)
- 添加 ::-webkit-scrollbar { display: none }(Chrome/Safari/Opera)
* feat: add sonner dependency for toast notifications
* refactor: remove DomainHeader component and its usage
* refactor: 使用 className 替换 sx/buttonSx 并优化 SwitchButtonGroup 选中动画
* refactor: 简化 TextInputArea,移除 showMessage 和 MUI 样式,改用 shadcn 样式和 sonner toast
* refactor: 简化 TextInputArea,移除 showMessage 和 MUI 样式,改用 shadcn 样式和 sonner toast
* refactor: 重构 QrCodePreview 组件,继承 HTMLDiv 属性并统一 shadcn 样式
- 组件改为继承 `React.HTMLAttributes<HTMLDivElement>`,支持外部传入 className 和事件
- 使用 `cn()` 函数合并外部类名
- 空白状态改用 `border border-dashed` 和更浅的 `bg-muted/40` 背景
- 正常状态改为纯白背景柔边圆角容器包裹二维码,确保暗黑模式下黑白对比度
- 下载/复制按钮完全对齐 shadcn 的 Outline 与 Default 样式规范
- 更新测试用例中的 alt 文本为 "QR Code Preview"
* refactor: 将 PageHeader 组件样式从 MUI sx 迁移至 Tailwind 类名,并更新测试
* refactor: 更新PageErrorBoundary的文案和样式以对齐shadcn主题
- 错误提示从“该页面加载失败”改为“该功能运行异常”
- 重试按钮文字从“重试”改为“重新尝试”
- 使用border-destructive, bg-destructive等语义化类名替换硬编码颜色
- 更新对应测试断言
* refactor: 重构 CopyButton 与 RouterContainer 组件,移除 GlobalSnackbar 并统一使用 sonner toast 和 cn 工具函数
* refactor: 移除 MUI sx 样式和未使用的 GlobalSnackbar 引用
* feat: add @radix-ui/react-select dependency
* feat: add Input and Select shadcn UI components
* refactor: 重构 Timestamp 页面使用响应式 Hook 统一状态并全面迁移至 shadcn 样式
* refactor: 将 TextStatistics 页面和 TextInputArea 组件全面迁移至 shadcn 样式并优化布局
* feat: add Badge, Checkbox, Label, and Switch shadcn UI components
* refactor: 全面迁移 StorageCleaner 页面至 shadcn 样式并移除 GlobalSnackbar 依赖
* refactor: 全面重构 JsonTools 页面,采用声明式响应架构并统一 shadcn 样式
* refactor: 全面重构 Jwt 页面,采用防抖输入并统一 shadcn 样式
* refactor: 重构 Dashboard 页面和 ToolCard 组件,全面迁移至 shadcn 样式并优化布局
* refactor: 重构 HtmlToMarkdown 和 MarkdownToHtml 页面,统一 shadcn 样式并优化打印与暗色模式
* refactor: 抽离 useBase64Converter hook 并新增 Base64ConverterSection 组件,统一 Base64 转换页面的 shadcn 样式
* refactor: 重构 QrCode 页面为声明式响应架构并统一 shadcn 样式
* refactor: 优化 Dashboard 布局及 ToolCard 描述文本截断处理
* refactor: 优化 MarkdownToHtml 预览样式,剥离 CSS 变量回退值并增强 iframe 暗色模式自适应
* refactor: 优化 Popover 安全性和交互体验,修复 Context Menu 数据持久化问题并添加 i18n 支持
* refactor: strengthen i18n type safety and fix async Promise handling in language detection
* refactor: extend vitest setup with full chrome/browser mocks and i18n utility mock
* refactor: migrate storage listeners to wxt/browser and refactor provider state management
* refactor: restructure CI/CD pipelines with cached dependencies, separate setup job, and multi-browser builds
* refactor: remove tsc check from lint-staged and reorder lint commands
* refactor: migrate eslint config to tseslint.config with projectService and upgrade React rules
* refactor: use __MSG_ placeholders for i18n and remove postcss config
* refactor: replace __MSG_ placeholders with static strings for extension name and description
* refactor: add React version detection and disable prop-types in eslint; refactor lazy translation tests with proper mock isolation and Chrome/browser stubs
* refactor: use regex matchers in StorageCleanerConfirm tests and add chrome/browser mocks
* refactor: use regex matchers for i18n text and add uniform mocks in test files
* ci: add wxt prepare step to generate .wxt types for typecheck and tests
---------
Co-authored-by: Ubuntu <ubuntu@localhost.localdomain>
This commit is contained in:
@@ -1,26 +1,52 @@
|
||||
import { Box, Switch, Typography } from '@mui/material';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import React from 'react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 引入官方的 Switch 原子组件
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
interface AutoRefreshToggleProps {
|
||||
interface AutoRefreshToggleProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {
|
||||
autoRefresh: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
}
|
||||
|
||||
export default function AutoRefreshToggle({ autoRefresh, onChange }: AutoRefreshToggleProps) {
|
||||
export default function AutoRefreshToggle({
|
||||
autoRefresh,
|
||||
onChange,
|
||||
className,
|
||||
...props
|
||||
}: AutoRefreshToggleProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
return (
|
||||
<Box sx={storageCleanerPageStyles.AUTO_REFRESH_CONTAINER}>
|
||||
<Typography variant="body2" fontWeight={700} sx={{ fontSize: '0.8rem', px: 1.2 }}>
|
||||
<div
|
||||
className={cn(
|
||||
// 外层包裹维持优雅的 shadcn 风格中性卡片,去除硬编码 mb-3 扩展灵活性
|
||||
'w-full p-4 rounded-xl border border-border bg-card text-card-foreground shadow-sm transition-all focus-within:ring-1 focus-within:ring-ring flex justify-between items-center',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 3. 使用标准的 shadcn/ui Label 组件:
|
||||
绑定 htmlFor 建立安全的表单无障碍桥梁,使得用户点击文字也能触发开关联动
|
||||
*/}
|
||||
<Label
|
||||
htmlFor="auto-refresh-switch"
|
||||
className="text-sm font-bold text-foreground cursor-pointer select-none tracking-tight"
|
||||
>
|
||||
{t('storageCleaner:autoRefresh')}
|
||||
</Typography>
|
||||
</Label>
|
||||
|
||||
{/* 4. 超进化:彻底废除 200 个字符的原生 checkbox 拼接!
|
||||
完美调用 shadcn 的 Switch 组件。它会自动应用全站统一的主色(Primary)、
|
||||
带阻尼的滑块硬件加速动效、以及教科书级别的 WAI-ARIA 无障碍键盘焦点提示。
|
||||
*/}
|
||||
<Switch
|
||||
size="small"
|
||||
id="auto-refresh-switch"
|
||||
checked={autoRefresh}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
color="warning"
|
||||
sx={storageCleanerPageStyles.AUTO_REFRESH_SWITCH}
|
||||
onCheckedChange={onChange}
|
||||
className="data-[state=checked]:bg-primary" // 如果依然需要特定的琥珀色可写 data-[state=checked]:bg-amber-500
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,27 +1,53 @@
|
||||
import { Alert, Box } from '@mui/material';
|
||||
import type { CleaningResult } from '@/types/storage';
|
||||
import React from 'react';
|
||||
import { CheckCircle, XCircle } from 'lucide-react';
|
||||
import type { CleaningResult as CleaningResultType } from '@/types/storage';
|
||||
import { formatCleaningResult } from '@/utils/storageCleaner';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils'; // 1. 引入 shadcn 核心类名合并工具
|
||||
|
||||
interface CleaningResultProps {
|
||||
result: CleaningResult | null;
|
||||
interface CleaningResultProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
result: CleaningResultType | null;
|
||||
}
|
||||
|
||||
export default function CleaningResult({ result }: CleaningResultProps) {
|
||||
export default function CleaningResult({ result, className, ...props }: CleaningResultProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
if (!result) return null;
|
||||
|
||||
const isSuccess = result.success;
|
||||
|
||||
return (
|
||||
<Box sx={{ mt: 3, animation: 'fadeIn 0.3s ease-in-out' }}>
|
||||
<Alert
|
||||
severity={result.success ? 'success' : 'error'}
|
||||
sx={storageCleanerPageStyles.CLEANING_RESULT_ALERT}
|
||||
<div
|
||||
className={cn('animate-in fade-in slide-in-from-top-1 duration-200 w-full', className)}
|
||||
{...props}
|
||||
>
|
||||
{/* 2. 彻底重构容器类名结构:
|
||||
- 成功状态:采用 Tailwind 官方推荐的 emerald 体系,利用 /10 (10% 透明度) 和 /20 (边框)。
|
||||
- 失败状态:完全放权给标准的 border-destructive/20 和 bg-destructive/5。
|
||||
- 这样在明暗双色模式切换时,色彩会自动与背景完美融为一体。
|
||||
*/}
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-start gap-3 rounded-xl py-2.5 px-3.5 border shadow-sm',
|
||||
isSuccess
|
||||
? 'bg-emerald-500/5 border-emerald-500/20 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-destructive/5 border-destructive/20 text-destructive',
|
||||
)}
|
||||
>
|
||||
{result.success
|
||||
? formatCleaningResult(result, t)
|
||||
: result.error || t('storageCleaner:partialFailure')}
|
||||
</Alert>
|
||||
</Box>
|
||||
{/* 3. 图标样式向系统语义全面对齐 */}
|
||||
{isSuccess ? (
|
||||
<CheckCircle className="h-4 w-4 shrink-0 mt-0.5 text-emerald-500" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 shrink-0 mt-0.5 text-destructive" />
|
||||
)}
|
||||
|
||||
{/* 4. 文本排版细节微调 */}
|
||||
<span className="text-xs sm:text-sm font-semibold leading-relaxed break-all">
|
||||
{isSuccess
|
||||
? formatCleaningResult(result, t)
|
||||
: result.error || t('storageCleaner:partialFailure')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { Box } from '@mui/material';
|
||||
import StorageIcon from '@mui/icons-material/Storage';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import { formatSize } from '@/utils/storageCleaner';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
|
||||
/**
|
||||
* DomainHeader 组件属性接口
|
||||
*/
|
||||
interface DomainHeaderProps {
|
||||
/** 当前域名 */
|
||||
domain: string;
|
||||
/** 已占用的存储大小(字节) */
|
||||
totalSize: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* DomainHeader - 存储清理页面标题栏组件
|
||||
*
|
||||
* 使用 PageHeader 组件构建,显示域名和已占用存储空间大小
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <DomainHeader
|
||||
* domain="example.com"
|
||||
* totalSize={1048576}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export default function DomainHeader({ domain, totalSize }: DomainHeaderProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
return (
|
||||
<PageHeader
|
||||
icon={<StorageIcon sx={{ fontSize: 22 }} />}
|
||||
iconColor={storageCleanerPageStyles.warningColor}
|
||||
title={t('storageCleaner:pageTitle')}
|
||||
subtitle={domain || t('storageCleaner:loading')}
|
||||
badge={
|
||||
totalSize > 0 ? (
|
||||
<Box sx={storageCleanerPageStyles.DOMAIN_HEADER_BADGE}>
|
||||
{t('storageCleaner:occupied', { size: formatSize(totalSize) })}
|
||||
</Box>
|
||||
) : null
|
||||
}
|
||||
iconSx={storageCleanerPageStyles.DOMAIN_HEADER_ICON}
|
||||
titleSx={{
|
||||
fontSize: '1rem',
|
||||
}}
|
||||
subtitleSx={{
|
||||
display: 'block',
|
||||
maxWidth: 240,
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
mt: 0.3,
|
||||
fontSize: '0.75rem',
|
||||
}}
|
||||
sx={{ mb: 3 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,44 +1,43 @@
|
||||
import { Box, Container, Typography } from '@mui/material';
|
||||
import WarningIcon from '@mui/icons-material/Warning';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ErrorDisplayProps {
|
||||
interface ErrorDisplayProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
error: string;
|
||||
}
|
||||
|
||||
export default function ErrorDisplay({ error }: ErrorDisplayProps) {
|
||||
export default function ErrorDisplay({ error, className, ...props }: ErrorDisplayProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
return (
|
||||
<Container sx={storageCleanerPageStyles.ERROR_DISPLAY_CONTAINER}>
|
||||
<Box sx={{ width: '100%', maxWidth: 320 }}>
|
||||
<Box sx={storageCleanerPageStyles.ERROR_DISPLAY_BOX}>
|
||||
<WarningIcon sx={{ fontSize: 36, color: 'error.main', mb: 2 }} />
|
||||
<Typography
|
||||
variant="body1"
|
||||
color="error.main"
|
||||
sx={{
|
||||
fontSize: '0.9rem',
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.4,
|
||||
mb: 3,
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 500,
|
||||
lineHeight: 1.4,
|
||||
}}
|
||||
>
|
||||
{t('storageCleaner:errorStandardOnly')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Container>
|
||||
// 1. 精简层级:单层外壳直接搞定居中、响应式高度与外部类名扩展
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center py-8 min-h-[240px] sm:min-h-[360px] p-4 text-center animate-in fade-in zoom-in-95 duration-200',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 2. 核心卡片容器:
|
||||
- 彻底放弃 bg-red-50,改用标准的 bg-destructive/5(3%~5% 透明度的系统危险色)。
|
||||
- 边框改为 border-destructive/20。
|
||||
- 这样在黑夜模式下会自动完美混色,绝不刺眼。
|
||||
*/}
|
||||
<div className="w-full max-w-xs flex flex-col items-center justify-center rounded-xl p-5 border border-destructive/20 bg-destructive/5 shadow-sm">
|
||||
{/* 3. 图标与主要错误信息全面对接 text-destructive 语义色 */}
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-destructive/10 text-destructive mb-3.5 shrink-0 animate-bounce [animation-duration:2s]">
|
||||
<AlertCircle className="h-5 w-5" />
|
||||
</div>
|
||||
|
||||
<p className="text-sm font-semibold leading-relaxed text-destructive break-all px-1 mb-2">
|
||||
{error}
|
||||
</p>
|
||||
|
||||
{/* 次要提示文本维持柔和的中性高级灰 */}
|
||||
<p className="text-xs font-medium leading-relaxed text-muted-foreground/90 px-2">
|
||||
{t('storageCleaner:errorStandardOnly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Box, Checkbox, Typography } from '@mui/material';
|
||||
import React from 'react';
|
||||
import { formatSize } from '@/utils/storageCleaner';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 引入官方的 Checkbox 原子组件
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
|
||||
interface OptionItemProps {
|
||||
interface OptionItemProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
labelKey: string;
|
||||
checked: boolean;
|
||||
size?: number;
|
||||
@@ -17,35 +19,63 @@ export default function OptionItem({
|
||||
size,
|
||||
isCount = false,
|
||||
onChange,
|
||||
className,
|
||||
...props
|
||||
}: OptionItemProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
return (
|
||||
<Box sx={storageCleanerPageStyles.OPTION_ITEM(checked)}>
|
||||
<Box sx={{ flex: 1, minWidth: 0, mr: 1.5 }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
fontWeight={700}
|
||||
sx={storageCleanerPageStyles.OPTION_ITEM_LABEL(checked)}
|
||||
<div
|
||||
// 3. 跨越级交互升级:将外部容器升级为一个高度敏感的可点击 Tab 热区
|
||||
onClick={onChange}
|
||||
className={cn(
|
||||
'flex justify-between items-center py-2.5 px-3.5 rounded-xl border cursor-pointer select-none transition-all duration-200',
|
||||
// 4. 彻底抛弃硬编码黄底:
|
||||
// - 选中时:使用 bg-primary/5 (系统主色超淡叠加) 配合标准 border-primary/30。
|
||||
// - 未选中时:保持透明 border-transparent,悬停呈现 bg-muted。
|
||||
// 这样在暗黑模式下会自动无缝混色,极为深邃、高级。
|
||||
checked
|
||||
? 'bg-primary/5 border-primary/30 shadow-sm'
|
||||
: 'bg-transparent border-transparent hover:bg-muted/70',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 左侧数据区域 */}
|
||||
<div className="flex-1 min-w-0 mr-4">
|
||||
<span
|
||||
className={cn(
|
||||
'block text-xs font-semibold leading-tight truncate transition-colors',
|
||||
checked ? 'text-foreground font-bold' : 'text-foreground/80',
|
||||
)}
|
||||
>
|
||||
{t(labelKey)}
|
||||
</Typography>
|
||||
</span>
|
||||
|
||||
{/* 底部容量大小或计数标识 */}
|
||||
{size !== undefined && size > 0 ? (
|
||||
<Typography variant="caption" sx={storageCleanerPageStyles.OPTION_ITEM_SIZE}>
|
||||
<span className="block text-[10px] font-mono font-medium text-muted-foreground/80 mt-0.5 tabular-nums">
|
||||
{isCount ? `${size} ${t('storageCleaner:countUnit')}` : formatSize(size)}
|
||||
</Typography>
|
||||
</span>
|
||||
) : (
|
||||
<Typography variant="caption" sx={storageCleanerPageStyles.OPTION_ITEM_NO_DATA}>
|
||||
<span className="block text-[10px] font-medium text-muted-foreground/60 mt-0.5 italic">
|
||||
{t('storageCleaner:noData')}
|
||||
</Typography>
|
||||
</span>
|
||||
)}
|
||||
</Box>
|
||||
</div>
|
||||
|
||||
{/* 5. 超进化:全面替换原生 input 标签
|
||||
完美调用 shadcn 的 Checkbox 组件。它自带全站统一的主色(Primary)、
|
||||
打钩选中时的平滑微放大缩放动效(Scale Animation),
|
||||
并且阻止冒泡,防范与外层的全局覆盖点击事件产生双重冲突。
|
||||
*/}
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={checked}
|
||||
onChange={onChange}
|
||||
color="warning"
|
||||
sx={storageCleanerPageStyles.OPTION_ITEM_CHECKBOX}
|
||||
// 阻止 Checkbox 自身的点击事件冒泡,因为外层 div 已经代理了点击逻辑
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={onChange}
|
||||
className="h-4 w-4 shrink-0 rounded border-input data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground"
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Box,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import type { StorageCleanerOptions } from '@/types/storage';
|
||||
import Button from '@/components/Button';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface StorageCleanerConfirmProps {
|
||||
open: boolean;
|
||||
@@ -32,69 +33,77 @@ export function StorageCleanerConfirm({
|
||||
.map(([key, _]) => t(`storageCleaner:options.${key as keyof StorageCleanerOptions}`));
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
fullWidth
|
||||
maxWidth="xs"
|
||||
slotProps={{
|
||||
paper: {
|
||||
sx: storageCleanerPageStyles.CONFIRM_DIALOG_PAPER,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DialogTitle sx={storageCleanerPageStyles.CONFIRM_DIALOG_TITLE}>
|
||||
{t('storageCleaner:confirmTitle')}
|
||||
</DialogTitle>
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
{/* 💡 终极修复秘诀:
|
||||
- 移除原来的 sm:max-w-[360px],改用 max-w-[calc(100%-32px)] 或者是 w-[88%]。
|
||||
- 这样无论插件弹窗多窄,它的左右两侧都必然会被强制挤出至少 16px 的完美空白护边!
|
||||
- 将 p-5 转换为明确的 p-6,增大弹窗内部的呼吸感。
|
||||
*/}
|
||||
<DialogContent
|
||||
className={cn(
|
||||
'w-[90%] max-w-[340px] p-6 gap-0 rounded-2xl overflow-hidden shadow-xl border border-border bg-card text-card-foreground',
|
||||
'animate-in fade-in-50 zoom-in-95 duration-200',
|
||||
)}
|
||||
>
|
||||
{/* 头部标题区域 */}
|
||||
<DialogHeader className="pt-1">
|
||||
<DialogTitle className="text-center text-lg font-bold tracking-tight text-foreground">
|
||||
{t('storageCleaner:confirmTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogContent sx={storageCleanerPageStyles.CONFIRM_DIALOG_CONTENT}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_DESC}
|
||||
>
|
||||
{t('storageCleaner:confirmDesc')}
|
||||
</Typography>
|
||||
{/* 内容主体:限制最大宽度,防止内部元素在大分辨率下被横向拉得太松散 */}
|
||||
<div className="text-center py-4 flex flex-col items-center w-full max-w-[280px] mx-auto">
|
||||
<DialogDescription className="mb-4 text-xs font-medium text-muted-foreground/90 leading-relaxed">
|
||||
{t('storageCleaner:confirmDesc')}
|
||||
</DialogDescription>
|
||||
|
||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1.2, justifyContent: 'center', mb: 4 }}>
|
||||
{selectedOptions.map((label) => (
|
||||
<Chip
|
||||
key={label}
|
||||
label={label}
|
||||
size="small"
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CHIP}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
{/* 待清理项目徽章群 */}
|
||||
<div className="flex flex-wrap gap-1.5 justify-center mb-5 w-full">
|
||||
{selectedOptions.map((label) => (
|
||||
<Badge
|
||||
key={label}
|
||||
variant="secondary"
|
||||
className="px-2.5 py-0.5 text-[11px] font-semibold border border-border/40 select-none bg-muted/60"
|
||||
>
|
||||
{label}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Box sx={storageCleanerPageStyles.CONFIRM_DIALOG_WARNING_BOX}>
|
||||
<Typography variant="caption" sx={storageCleanerPageStyles.CONFIRM_DIALOG_WARNING_TEXT}>
|
||||
<span role="img" aria-label="warning">
|
||||
⚠️
|
||||
</span>{' '}
|
||||
{t('storageCleaner:irreversible')}
|
||||
</Typography>
|
||||
</Box>
|
||||
{/* 风险警告横幅 */}
|
||||
<div className="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 rounded-lg bg-destructive/5 border border-dashed border-destructive/20 w-full max-w-[240px] animate-pulse [animation-duration:3s]">
|
||||
<AlertTriangle className="h-3.5 w-3.5 text-destructive shrink-0" />
|
||||
<span className="text-[11px] font-bold text-destructive leading-none tracking-tight">
|
||||
{t('storageCleaner:irreversible')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部操作按钮区:
|
||||
💡 修复要点:
|
||||
- 增加 pt-2 隔开上方危险条。
|
||||
- 显式通过 w-full 配合 flex-col 铺满,在移动端/窄插件下垂直堆叠,最符合小屏直觉。
|
||||
*/}
|
||||
<DialogFooter className="flex flex-col gap-2 w-full pt-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={onConfirm}
|
||||
className="w-full text-xs font-bold shadow-sm h-9"
|
||||
>
|
||||
{t('storageCleaner:confirmAction')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
className="w-full text-xs font-semibold shadow-sm h-9 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t('common:buttons.cancel')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions sx={{ p: 3, pt: 1, gap: 2 }}>
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={onClose}
|
||||
fullWidth
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CANCEL}
|
||||
>
|
||||
{t('common:buttons.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={onConfirm}
|
||||
fullWidth
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CONFIRM}
|
||||
>
|
||||
{t('storageCleaner:confirmAction')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { Box, Checkbox, Divider, Grid, Typography } from '@mui/material';
|
||||
import React from 'react';
|
||||
import type { StorageCleanerOptions } from '@/types/storage';
|
||||
import OptionItem from './OptionItem';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 1. 引入官方标准的 Checkbox 原子组件
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
interface StorageOptionsGridProps {
|
||||
interface StorageOptionsGridProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
options: StorageCleanerOptions;
|
||||
sizes: Record<string, number>;
|
||||
allSelected: boolean;
|
||||
someSelected: boolean;
|
||||
someSelected: boolean; // 重新激活半选状态
|
||||
onOptionChange: (key: keyof StorageCleanerOptions) => void;
|
||||
onSelectAll: (checked: boolean) => void;
|
||||
}
|
||||
@@ -20,6 +23,8 @@ export default function StorageOptionsGrid({
|
||||
someSelected,
|
||||
onOptionChange,
|
||||
onSelectAll,
|
||||
className,
|
||||
...props
|
||||
}: StorageOptionsGridProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
@@ -32,41 +37,62 @@ export default function StorageOptionsGrid({
|
||||
{ key: 'serviceWorkers', isCount: true },
|
||||
];
|
||||
|
||||
// 2. 处理全选栏点击事件:包裹整个栏变成超级热区
|
||||
const handleToggleAll = () => {
|
||||
// 如果当前已经是全选,点击则取消全选;否则,点击就是全选
|
||||
onSelectAll(!allSelected);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={storageCleanerPageStyles.OPTIONS_GRID_CONTAINER}>
|
||||
<Box sx={{ p: 1.2 }}>
|
||||
<Grid container spacing={1.5}>
|
||||
<div
|
||||
className={cn(
|
||||
'w-full rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden transition-all',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 核心网格区 */}
|
||||
<div className="p-3">
|
||||
{/* 💡 优化点:加入 items-stretch,确保左右卡片高度绝对对齐 */}
|
||||
<div className="grid grid-cols-2 gap-2.5 items-stretch">
|
||||
{optionKeys.map(({ key, isCount }) => (
|
||||
<Grid size={6} key={key}>
|
||||
<OptionItem
|
||||
labelKey={`storageCleaner:options.${key}`}
|
||||
checked={options[key]}
|
||||
size={sizes[key]}
|
||||
isCount={isCount}
|
||||
onChange={() => onOptionChange(key)}
|
||||
/>
|
||||
</Grid>
|
||||
/* 💡 终极修复:直接把 key 挂在 OptionItem 上,移除了无意义的包裹 div */
|
||||
<OptionItem
|
||||
key={key}
|
||||
labelKey={`storageCleaner:options.${key}`}
|
||||
checked={options[key]}
|
||||
size={sizes[key]}
|
||||
isCount={isCount}
|
||||
onChange={() => onOptionChange(key)}
|
||||
/>
|
||||
))}
|
||||
</Grid>
|
||||
</Box>
|
||||
<Divider sx={{ mx: 0, borderColor: 'divider' }} />
|
||||
<Box sx={storageCleanerPageStyles.OPTIONS_GRID_FOOTER}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
fontWeight={700}
|
||||
sx={{ color: 'text.secondary', fontSize: '0.7rem', px: 0 }}
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3. 全选功能底护栏超进化:
|
||||
- 整体赋予 cursor-pointer 和 onClick,点击一整行都能触发全选。
|
||||
- 悬停时自动变色提示可点击 (hover:bg-muted/50)。
|
||||
*/}
|
||||
<div
|
||||
onClick={handleToggleAll}
|
||||
className="border-t border-border flex justify-between items-center px-4 py-2.5 bg-muted/20 hover:bg-muted/50 transition-colors cursor-pointer select-none"
|
||||
>
|
||||
<Label className="text-xs font-bold text-muted-foreground/90 cursor-pointer">
|
||||
{t('storageCleaner:selectAll')}
|
||||
</Typography>
|
||||
</Label>
|
||||
|
||||
{/* 4. 降维打击:调用标准的 shadcn/ui Checkbox
|
||||
- 阻止冒泡:防止事件重复触发。
|
||||
- 完美注入半选逻辑:当 allSelected 为 false 但 someSelected 为 true 时,
|
||||
组件会自动呈现优雅的 "—" (减号) 半选视觉状态,向主流系统控制台高标准看齐!
|
||||
*/}
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={allSelected}
|
||||
indeterminate={someSelected}
|
||||
onChange={(e) => onSelectAll(e.target.checked)}
|
||||
color="warning"
|
||||
sx={storageCleanerPageStyles.OPTIONS_GRID_CHECKBOX}
|
||||
checked={allSelected ? true : someSelected ? 'indeterminate' : false}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={(checked) => onSelectAll(checked === true)}
|
||||
className="h-4 w-4 shrink-0 rounded border-input data-[state=checked]:bg-primary data-[state=indeterminate]:bg-primary"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { Box, CircularProgress, Container } from '@mui/material';
|
||||
import Button from '@/components/Button';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { Loader2 } from 'lucide-react'; // 引入标准的高级阻尼 Spinner 图标
|
||||
import { Button } from '@/components/ui/button';
|
||||
import StorageCleanerConfirm from '@/pages/StorageCleaner/StorageCleanerConfirm';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useStorageCleaner } from './useStorageCleaner';
|
||||
import DomainHeader from './DomainHeader';
|
||||
import StorageOptionsGrid from './StorageOptionsGrid';
|
||||
import AutoRefreshToggle from './AutoRefreshToggle';
|
||||
import ErrorDisplay from './ErrorDisplay';
|
||||
@@ -12,10 +9,10 @@ import CleaningResult from './CleaningResult';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
|
||||
export default function Index() {
|
||||
const { showMessage } = useSnackbar();
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
// 1. 完美对接全新重构、无需回调参数的纯净版状态 Hook
|
||||
const {
|
||||
domain,
|
||||
error,
|
||||
isInitializing,
|
||||
options,
|
||||
@@ -25,64 +22,85 @@ export default function Index() {
|
||||
result,
|
||||
showConfirm,
|
||||
setShowConfirm,
|
||||
totalSize,
|
||||
allSelected,
|
||||
someSelected,
|
||||
handleAutoRefreshChange,
|
||||
handleOptionChange,
|
||||
handleSelectAll,
|
||||
handleClean,
|
||||
} = useStorageCleaner({ showMessage });
|
||||
} = useStorageCleaner();
|
||||
|
||||
const isDisabled = !(someSelected || allSelected) || loading;
|
||||
// 计算当前的按钮锁定状态:没有任何一项被勾选,或者正在清理中,则禁用大按钮
|
||||
const isButtonDisabled = !(someSelected || allSelected) || loading;
|
||||
|
||||
// 2. 初始化骨架屏:全面升级为符合 shadcn 规范的无损微动效 Spinner
|
||||
if (isInitializing) {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||
<CircularProgress size={24} color="warning" />
|
||||
</Box>
|
||||
<div className="flex flex-col items-center justify-center py-12 min-h-[280px] w-full animate-in fade-in duration-200">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground/80" />
|
||||
<span className="text-xs text-muted-foreground mt-2 font-medium tracking-wide">
|
||||
正在读取站点数据...
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 拦截非法域名或受限域名的错误提示页(ErrorDisplay 内部已在上一轮做好 p-4 居中)
|
||||
if (error) {
|
||||
return <ErrorDisplay error={error} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Container sx={{ py: 2 }}>
|
||||
<DomainHeader domain={domain} totalSize={totalSize} />
|
||||
/* 3. 终极版页面根容器:
|
||||
- 彻底灌入 p-4,全局对齐线向内收缩 16px,终结贴边惨剧。
|
||||
- 用 space-y-3.5 替代块级外边距(mb-3 等),让所有卡片之间的垂直间距处于绝对一致的黄金比例。
|
||||
*/
|
||||
<div className="p-4 w-full flex flex-col space-y-3.5 animate-in fade-in duration-300">
|
||||
{/* 存储网格核心中控面板 (内部已满血复活半选状态) */}
|
||||
<StorageOptionsGrid
|
||||
options={options}
|
||||
sizes={sizes}
|
||||
allSelected={allSelected}
|
||||
someSelected={someSelected}
|
||||
onOptionChange={handleOptionChange}
|
||||
onSelectAll={handleSelectAll}
|
||||
/>
|
||||
|
||||
<StorageOptionsGrid
|
||||
options={options}
|
||||
sizes={sizes}
|
||||
allSelected={allSelected}
|
||||
someSelected={someSelected}
|
||||
onOptionChange={handleOptionChange}
|
||||
onSelectAll={handleSelectAll}
|
||||
/>
|
||||
{/* 自动刷新开关 */}
|
||||
<AutoRefreshToggle autoRefresh={autoRefresh} onChange={handleAutoRefreshChange} />
|
||||
|
||||
<AutoRefreshToggle autoRefresh={autoRefresh} onChange={handleAutoRefreshChange} />
|
||||
{/* 4. 主行动按钮超进化:
|
||||
- 彻底剥离 bg-amber-500,全面回归系统标准的 variant="destructive"。
|
||||
- 享受高风险操作该有的危险红警示,完美契合上一轮重构的二次确认弹窗基调。
|
||||
- 高级动态加载:当处于 cleaning 状态时,文字自动流转,且左侧自动淡入等宽 Loader2 图标。
|
||||
*/}
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="default"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
disabled={isButtonDisabled}
|
||||
className="w-full h-10 font-bold shadow-sm text-sm tracking-wide transition-all active:scale-[0.99]"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('storageCleaner:cleaning')}
|
||||
</>
|
||||
) : (
|
||||
t('storageCleaner:cleanNow')
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CONFIRM}
|
||||
disabled={isDisabled}
|
||||
fullWidth
|
||||
>
|
||||
{loading ? t('storageCleaner:cleaning') : t('storageCleaner:cleanNow')}
|
||||
</Button>
|
||||
|
||||
<CleaningResult result={result} />
|
||||
</Container>
|
||||
{/* 动态清理结果返回反馈卡片 */}
|
||||
<CleaningResult result={result} />
|
||||
|
||||
{/* 二次风险防御确认弹窗 */}
|
||||
<StorageCleanerConfirm
|
||||
open={showConfirm}
|
||||
onClose={() => setShowConfirm(false)}
|
||||
onConfirm={handleClean}
|
||||
options={options}
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import type { SnackbarOptions } from '@/components/GlobalSnackbar';
|
||||
import type {
|
||||
CleaningResult,
|
||||
StorageCleanerOptions,
|
||||
@@ -11,14 +10,15 @@ import {
|
||||
getCacheStorageSize,
|
||||
getCookieSize,
|
||||
getCurrentTab,
|
||||
getOriginStorageEstimate,
|
||||
getLocalStorageSize,
|
||||
getOriginStorageEstimate,
|
||||
getServiceWorkerCount,
|
||||
getSessionStorageSize,
|
||||
isRestrictedUrl,
|
||||
} from '@/utils/storageCleaner';
|
||||
import { MessageAction, sendMessage } from '@/utils/messages';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { toast } from 'sonner'; // 1. 直接引用 shadcn 推荐的 Sonner 单例通知,踢出回调依赖
|
||||
|
||||
const DEFAULT_OPTIONS: StorageCleanerOptions = {
|
||||
localStorage: true,
|
||||
@@ -35,7 +35,6 @@ const DEFAULT_PREFERENCES: StorageCleanerPreferences = {
|
||||
};
|
||||
|
||||
export interface UseStorageCleanerReturn {
|
||||
// State
|
||||
domain: string;
|
||||
error: string;
|
||||
isInitializing: boolean;
|
||||
@@ -46,26 +45,17 @@ export interface UseStorageCleanerReturn {
|
||||
result: CleaningResult | null;
|
||||
showConfirm: boolean;
|
||||
setShowConfirm: (show: boolean) => void;
|
||||
|
||||
// Computed
|
||||
totalSize: number;
|
||||
allSelected: boolean;
|
||||
someSelected: boolean;
|
||||
|
||||
// Handlers
|
||||
handleAutoRefreshChange: (checked: boolean) => Promise<void>;
|
||||
handleOptionChange: (key: keyof StorageCleanerOptions) => Promise<void>;
|
||||
handleSelectAll: (checked: boolean) => Promise<void>;
|
||||
handleAutoRefreshChange: (checked: boolean) => void;
|
||||
handleOptionChange: (key: keyof StorageCleanerOptions) => void;
|
||||
handleSelectAll: (checked: boolean) => void;
|
||||
handleClean: () => Promise<void>;
|
||||
}
|
||||
|
||||
export interface UseStorageCleanerOptions {
|
||||
showMessage: (message: string, options?: SnackbarOptions) => void;
|
||||
}
|
||||
|
||||
export function useStorageCleaner({
|
||||
showMessage,
|
||||
}: UseStorageCleanerOptions): UseStorageCleanerReturn {
|
||||
export function useStorageCleaner(): UseStorageCleanerReturn {
|
||||
const { t } = useLazyTranslation(['storageCleaner', 'common']);
|
||||
const [domain, setDomain] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
@@ -79,6 +69,7 @@ export function useStorageCleaner({
|
||||
|
||||
const requestIdRef = useRef<number>(0);
|
||||
const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const storageTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const loadingRef = useRef(loading);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -88,9 +79,11 @@ export function useStorageCleaner({
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
|
||||
if (storageTimerRef.current) clearTimeout(storageTimerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 核心数据拉取链条
|
||||
const loadInfo = useCallback(async () => {
|
||||
const currentRequestId = ++requestIdRef.current;
|
||||
try {
|
||||
@@ -149,16 +142,14 @@ export function useStorageCleaner({
|
||||
});
|
||||
|
||||
const debouncedLoadInfo = useCallback(() => {
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
loadInfoRef.current().catch(console.error);
|
||||
}, 300);
|
||||
}, []);
|
||||
|
||||
// 监听浏览器标签行为
|
||||
useEffect(() => {
|
||||
// 首次加载不防抖
|
||||
loadInfoRef.current().catch(console.error);
|
||||
|
||||
const handleTabChange = () => debouncedLoadInfo();
|
||||
@@ -176,90 +167,91 @@ export function useStorageCleaner({
|
||||
chrome.tabs.onActivated.removeListener(handleTabChange);
|
||||
chrome.tabs.onUpdated.removeListener(handleTabUpdated);
|
||||
chrome.windows.onFocusChanged.removeListener(handleTabChange);
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [debouncedLoadInfo]);
|
||||
|
||||
const handleAutoRefreshChange = useCallback(
|
||||
async (checked: boolean) => {
|
||||
setAutoRefresh(checked);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh: checked,
|
||||
selectedTypes: options,
|
||||
});
|
||||
},
|
||||
[options],
|
||||
);
|
||||
// 2. 超进化:防抖写盘管道 (Chrome Storage Debounce Pipeline)
|
||||
// 用户疯狂点击勾选时,React 状态保持丝滑的 0 延迟同步,只有停下点击 500ms 后,才会真正发起一次 Chrome 存盘,配额永远安全。
|
||||
useEffect(() => {
|
||||
// 过滤掉首次初始化时的无意义写盘
|
||||
if (isInitializing) return;
|
||||
|
||||
const handleOptionChange = useCallback(
|
||||
async (key: keyof StorageCleanerOptions) => {
|
||||
const newOptions = { ...options, [key]: !options[key] };
|
||||
setOptions(newOptions);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: newOptions,
|
||||
});
|
||||
},
|
||||
[options, autoRefresh],
|
||||
);
|
||||
if (storageTimerRef.current) clearTimeout(storageTimerRef.current);
|
||||
storageTimerRef.current = setTimeout(async () => {
|
||||
await storageUtil
|
||||
.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: options,
|
||||
})
|
||||
.catch(console.error);
|
||||
}, 500);
|
||||
}, [options, autoRefresh, isInitializing]);
|
||||
|
||||
const handleSelectAll = useCallback(
|
||||
async (checked: boolean) => {
|
||||
const newOptions = {
|
||||
localStorage: checked,
|
||||
sessionStorage: checked,
|
||||
indexedDB: checked,
|
||||
cookies: checked,
|
||||
cacheStorage: checked,
|
||||
serviceWorkers: checked,
|
||||
};
|
||||
setOptions(newOptions);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: newOptions,
|
||||
});
|
||||
},
|
||||
[autoRefresh],
|
||||
);
|
||||
// 3. 极速状态分发:同步函数化(去掉了原有的 async 声明,只负责触发状态)
|
||||
const handleAutoRefreshChange = useCallback((checked: boolean) => {
|
||||
setAutoRefresh(checked);
|
||||
}, []);
|
||||
|
||||
const handleOptionChange = useCallback((key: keyof StorageCleanerOptions) => {
|
||||
setOptions((prev) => ({ ...prev, [key]: !prev[key] }));
|
||||
}, []);
|
||||
|
||||
const handleSelectAll = useCallback((checked: boolean) => {
|
||||
setOptions({
|
||||
localStorage: checked,
|
||||
sessionStorage: checked,
|
||||
indexedDB: checked,
|
||||
cookies: checked,
|
||||
cacheStorage: checked,
|
||||
serviceWorkers: checked,
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 清理动作核心
|
||||
const handleClean = useCallback(async () => {
|
||||
if (loadingRef.current) {
|
||||
return;
|
||||
}
|
||||
if (loadingRef.current) return;
|
||||
|
||||
const tab = await getCurrentTab();
|
||||
if (!tab || !tab.id || !tab.url) {
|
||||
showMessage(t('storageCleaner:errorNoTab'), { severity: 'warning' });
|
||||
toast.warning(t('storageCleaner:errorNoTab'));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const cleaningResult = await clearStorage(tab.id, tab.url, options);
|
||||
setResult(cleaningResult);
|
||||
|
||||
if (autoRefresh && cleaningResult.success) {
|
||||
showMessage(t('storageCleaner:cleanSuccessReload'), { severity: 'success' });
|
||||
toast.success(t('storageCleaner:cleanSuccessReload'));
|
||||
await sendMessage(MessageAction.RELOAD_TAB, { tabId: tab.id, delay: 1000 });
|
||||
} else {
|
||||
await loadInfo();
|
||||
}
|
||||
} catch (err) {
|
||||
showMessage(`${t('storageCleaner:cleanError')}: ${String(err)}`, { severity: 'error' });
|
||||
toast.error(`${t('storageCleaner:cleanError')}: ${String(err)}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setShowConfirm(false);
|
||||
}
|
||||
}, [options, autoRefresh, showMessage, loadInfo, t]);
|
||||
}, [options, autoRefresh, loadInfo, t]);
|
||||
|
||||
const totalSize =
|
||||
(sizes.cookies || 0) +
|
||||
(sizes.localStorage || 0) +
|
||||
(sizes.sessionStorage || 0) +
|
||||
(sizes.indexedDB || 0);
|
||||
// 4. 精准的流式衍生计算收拢:完全切断垃圾内存常态分配
|
||||
const totalSize = useMemo(() => {
|
||||
return (
|
||||
(sizes.cookies || 0) +
|
||||
(sizes.localStorage || 0) +
|
||||
(sizes.sessionStorage || 0) +
|
||||
(sizes.indexedDB || 0)
|
||||
);
|
||||
}, [sizes]);
|
||||
|
||||
const allSelected = Object.values(options).every(Boolean);
|
||||
const someSelected = Object.values(options).some(Boolean) && !allSelected;
|
||||
const selectionMetrics = useMemo(() => {
|
||||
const vals = Object.values(options);
|
||||
const all = vals.every(Boolean);
|
||||
const some = vals.some(Boolean) && !all;
|
||||
return { all, some };
|
||||
}, [options]);
|
||||
|
||||
return {
|
||||
domain,
|
||||
@@ -273,8 +265,8 @@ export function useStorageCleaner({
|
||||
showConfirm,
|
||||
setShowConfirm,
|
||||
totalSize,
|
||||
allSelected,
|
||||
someSelected,
|
||||
allSelected: selectionMetrics.all,
|
||||
someSelected: selectionMetrics.some,
|
||||
handleAutoRefreshChange,
|
||||
handleOptionChange,
|
||||
handleSelectAll,
|
||||
|
||||
Reference in New Issue
Block a user