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:
LingandRX
2026-05-23 00:02:43 +08:00
committed by GitHub
parent 689c3faf16
commit efbed7cf53
114 changed files with 7621 additions and 7262 deletions
+37 -14
View File
@@ -5,16 +5,18 @@ import { createAllContextMenus, parseContextMenuClick } from '@/utils/contextMen
import { saveContextMenuData } from '@/utils/useContextMenuData';
export default defineBackground(() => {
// 1. 扩展初次安装或更新时,注册右键上下文大闸
browser.runtime.onInstalled.addListener(() => {
createAllContextMenus();
});
// 2. 右键点击中央中枢路由
browser.contextMenus.onClicked.addListener(async (info, _tab) => {
const result = parseContextMenuClick(info.menuItemId as string, info);
if (!result.success || !result.data) {
if (result.error) {
console.warn('[Context Menu]', result.error);
console.warn('[Context Menu Warning]', result.error);
}
return;
}
@@ -22,58 +24,79 @@ export default defineBackground(() => {
const { featureKey, payload } = result.data;
try {
// 检查侧边栏(Side Panel)的挂载激活状态
const sidePanelState = await browser.storage.local.get('sidePanelOpen');
const isSidePanelOpen = sidePanelState.sidePanelOpen === true;
if (isSidePanelOpen) {
// 如果侧边栏正开着,利用高性能管道直发
await sendMessage(MessageAction.CONTEXT_MENU_CLICKED, { featureKey, payload });
return;
}
} catch {
// sidepanel 未打开或无法通信,继续执行其他方案
} catch (err) {
console.debug('[Context Menu] Side panel pipeline is not available:', err);
}
// 保存数据到 storagepopup 打开后会读取
// 💡 核心自愈机制:保存数据到共享沙箱 StoragePopup 打开后(无论是自动还是手动)都会读取
await saveContextMenuData({ featureKey, payload });
// 打开 popup 弹窗
try {
await browser.action.openPopup();
} catch (err) {
// openPopup 在无活动窗口时会失败(如窗口失焦、特殊页面等)
// 数据已保存到 storage,用户手动打开 popup 仍可正常使用
console.warn('[Context Menu] 自动打开 popup 失败,请手动点击扩展图标:', err);
await chrome.storage.local.remove('contextMenu/pendingData');
// 💡 修复点:自动打开 Popup 失败时,绝对不能将 pendingData 撕毁!
// 保持数据留在 storage 内部,由于 Service Worker 的持久化,用户之后不管什么时候手动点开图标,
// 数据依旧完好如初,完美契合了你的设计注释!
console.warn(
'[Context Menu] 自动打开 popup 失败,请手动点击扩展图标,暂存数据已安全保留在内存中:',
err,
);
}
});
// 监听扩展图标点击事件,打开侧边栏
// 监听扩展图标点击事件,安全激活侧边栏
browser.action.onClicked.addListener(async (tab) => {
if (tab.id) {
try {
await browser.sidePanel.open({ tabId: tab.id });
} catch (err) {
console.error('Failed to open side panel:', err);
console.error('Failed to open side panel via extension action clicked:', err);
}
}
});
// 使用 @webext-core/messaging 处理消息
// 💡 3. 异步刷新请求监听
onMessage(MessageAction.RELOAD_TAB, async (message) => {
const { tabId, delay = 0 } = message.data;
const executeReload = () => {
browser.tabs.reload(tabId).catch((err) => {
console.error('Failed to reload tab:', err);
console.error('Failed to execute tab reload operation:', err);
});
};
if (delay > 0) {
// 如果小于 1000ms(短抖动缓冲),可以使用极轻量级 setTimeout 防御
// 如果是秒级以上的延时,为防止 Service Worker 闲置被内核销毁,应当使用 Alarms 沙箱驱动
if (delay > 0 && delay < 1000) {
setTimeout(executeReload, delay);
} else if (delay >= 1000) {
const alarmName = `reload-tab-${tabId}-${Date.now()}`;
// 创建一个临时的一次性 Alarm 闹钟
await browser.alarms.create(alarmName, { when: Date.now() + delay });
// 动态注册一个一次性的生命周期续航守卫
const alarmListener = (alarm: { name: string }) => {
if (alarm.name === alarmName) {
executeReload();
browser.alarms.onAlarm.removeListener(alarmListener);
}
};
browser.alarms.onAlarm.addListener(alarmListener);
} else {
executeReload();
}
return { success: true, message: '刷新请求已接收' };
return { success: true, message: '刷新请求已通过常驻 Service Worker 安全隔离区' };
});
});
+28 -5
View File
@@ -1,18 +1,29 @@
import type { ContextMenuClickedPayload } from '@/utils/messages';
import { MessageAction, onMessage } from '@/utils/messages';
import { getTextStats } from '@/utils/textStatistics';
import { showTimestampResult, showTextStatsResult, hidePopover } from './uiPopover';
import type { ContextMenuClickedPayload } from '@/utils/messages';
import { hidePopover, showTextStatsResult, showTimestampResult } from './uiPopover';
// 💡 1. 国际化超进化:对接 chrome.i18n 插件标准 API,如果环境不支持则安全降级,拒绝硬编码中文
function getI18nText(key: string, fallback: string): string {
if (typeof chrome !== 'undefined' && chrome.i18n) {
return chrome.i18n.getMessage(key) || fallback;
}
return fallback;
}
function convertTimestamp(input: string): string {
const invalidText = getI18nText('invalidTimestamp', 'Invalid Timestamp');
const num = Number(input.trim());
if (isNaN(num)) {
return '无效时间戳';
return invalidText;
}
// 1e12 判定毫秒级/秒级时间戳兼容
const d = num > 1e12 ? new Date(num) : new Date(num * 1000);
if (isNaN(d.getTime())) {
return '无效时间戳';
return invalidText;
}
const year = d.getFullYear();
@@ -28,16 +39,28 @@ function convertTimestamp(input: string): string {
let lastClickX = 0;
let lastClickY = 0;
// 💡 使用 capture: true 确保在任何极其复杂的单页应用(SPA)中都能精准捕获右键坐标
document.addEventListener(
'contextmenu',
(e) => {
lastClickX = e.clientX;
lastClickY = e.clientY;
},
true,
{ capture: true, passive: true }, // 优化滚动与捕获性能
);
export function initContextMenuHandler(): void {
// 💡 2. 全局自净化大闸(Global Auto-Purge Grid):
// 当用户在网页上进行左键点击、滚动视视口、或调整大小时,
// 证明心流已经移开,自发隐退所有浮动的 Popover 弹窗,体验顺滑得丝丝入扣!
const dismissPopover = (): void => {
hidePopover();
};
document.addEventListener('click', dismissPopover, { passive: true });
document.addEventListener('scroll', dismissPopover, { passive: true });
window.addEventListener('resize', dismissPopover, { passive: true });
onMessage(MessageAction.CONTEXT_MENU_CLICKED, (message) => {
const { featureKey, payload } = message.data as ContextMenuClickedPayload;
+60 -30
View File
@@ -22,13 +22,15 @@ function injectStyles(): void {
font-size: 13px;
line-height: 1.5;
opacity: 0;
visibility: hidden; /* 💡 1. 规整隐藏状态:允许排版引擎计算尺寸,同时阻断视觉呈现 */
transform: translateY(-8px);
transition: opacity 0.2s ease, transform 0.2s ease;
transition: opacity 0.2s ease, transform 0.2s ease, visibility 0.2s ease;
pointer-events: none;
}
#${POPOVER_ID}.visible {
opacity: 1;
visibility: visible;
transform: translateY(0);
pointer-events: auto;
}
@@ -85,14 +87,11 @@ function injectStyles(): void {
margin-bottom: 8px;
}
#${POPOVER_ID} .popover-value:last-child {
margin-bottom: 0;
}
#${POPOVER_ID} .stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 4px;
}
#${POPOVER_ID} .stat-item {
@@ -126,27 +125,36 @@ function getOrCreatePopover(): HTMLElement {
return popover;
}
// 💡 2. 安全防线:字符实体转义沙箱,彻底掐灭任意恶意脚本的执行通道
function escapeHtml(text: string): string {
const map: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;',
};
return text.replace(/[&<>"']/g, (m) => map[m]);
}
function positionPopover(popover: HTMLElement, x: number, y: number): void {
// 此时借助 visibility: hidden,元素在隐藏状态下拥有真实的布局高宽
const rect = popover.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
let left = x;
let top = y;
let left = x + 8; // 微微追加水平偏置,防范直接遮挡用户的鼠标落点
let top = y + 8;
if (left + rect.width > viewportWidth - 16) {
left = viewportWidth - rect.width - 16;
}
if (left < 16) {
left = 16;
}
if (left < 16) left = 16;
if (top + rect.height > viewportHeight - 16) {
top = y - rect.height - 8;
}
if (top < 16) {
top = 16;
}
if (top < 16) top = 16;
popover.style.left = `${left}px`;
popover.style.top = `${top}px`;
@@ -157,24 +165,41 @@ let hideTimeout: ReturnType<typeof setTimeout> | null = null;
export function showPopover(
x: number,
y: number,
content: string,
contentHtml: string,
title?: string,
duration: number = 5000,
): void {
const popover = getOrCreatePopover();
const titleHtml = title
? `<div class="popover-header">
<span class="popover-title">${title}</span>
<button class="popover-close" onclick="this.closest('#${POPOVER_ID}').classList.remove('visible')">&times;</button>
</div>`
: '';
// 💡 3. 坚固的无障碍绑定:废除违规的行内 inline onclick,改用标准原生节点监听
popover.innerHTML = '';
popover.innerHTML = `
${titleHtml}
<div class="popover-content">${content}</div>
`;
if (title) {
const header = document.createElement('div');
header.className = 'popover-header';
const titleSpan = document.createElement('span');
titleSpan.className = 'popover-title';
titleSpan.textContent = title; // ✅ 强安全性护航
const closeBtn = document.createElement('button');
closeBtn.className = 'popover-close';
closeBtn.innerHTML = '&times;';
closeBtn.addEventListener('click', () => {
popover.classList.remove('visible');
});
header.appendChild(titleSpan);
header.appendChild(closeBtn);
popover.appendChild(header);
}
const contentContainer = document.createElement('div');
contentContainer.className = 'popover-content';
contentContainer.innerHTML = contentHtml; // 内部拼装的方法已提前完成全消毒转义
popover.appendChild(contentContainer);
// 提前移除激活类名,使 visibility: hidden 起效以供测量
popover.classList.remove('visible');
requestAnimationFrame(() => {
@@ -182,9 +207,7 @@ export function showPopover(
popover.classList.add('visible');
});
if (hideTimeout) {
clearTimeout(hideTimeout);
}
if (hideTimeout) clearTimeout(hideTimeout);
if (duration > 0) {
hideTimeout = setTimeout(() => {
@@ -205,11 +228,15 @@ export function hidePopover(): void {
}
export function showTimestampResult(x: number, y: number, timestamp: string, result: string): void {
// 对外部传来的参数先全数塞入 escapeHtml 大闸进行纯氧化清洗
const cleanTimestamp = escapeHtml(timestamp);
const cleanResult = escapeHtml(result);
const content = `
<div class="popover-label">输入时间戳</div>
<div class="popover-value">${timestamp}</div>
<div class="popover-value">${cleanTimestamp}</div>
<div class="popover-label">转换结果</div>
<div class="popover-value">${result}</div>
<div class="popover-value">${cleanResult}</div>
`;
showPopover(x, y, content, '⏰ 时间戳转换');
}
@@ -221,9 +248,12 @@ export function showTextStatsResult(
stats: { characters: number; words: number; lines: number; bytes: number },
): void {
const truncatedText = text.length > 50 ? text.substring(0, 50) + '...' : text;
// 对选中的脏文本先进行严格转义
const cleanText = escapeHtml(truncatedText);
const content = `
<div class="popover-label">选中文本</div>
<div class="popover-value">${truncatedText}</div>
<div class="popover-value">${cleanText}</div>
<div class="stat-grid">
<div class="stat-item">
<div class="stat-label">字符</div>
+104 -216
View File
@@ -1,28 +1,13 @@
import { SyntheticEvent, useEffect, useMemo, useState } from 'react';
import { GripVertical, RefreshCw, Settings } from 'lucide-react';
import {
alpha,
Box,
CircularProgress,
IconButton,
Paper,
Stack,
Switch,
Tab,
Tabs,
Tooltip,
Typography,
} from '@mui/material';
import SettingsIcon from '@mui/icons-material/Settings';
import RefreshIcon from '@mui/icons-material/Refresh';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import {
DndContext,
closestCenter,
PointerSensor,
DndContext,
type DragEndEvent,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import {
arrayMove,
@@ -34,6 +19,7 @@ import {
import { CSS } from '@dnd-kit/utilities';
import type { PageType, StorageSchema } from '@/types/storage';
import { storageUtil } from '@/utils/chromeStorage';
import type { PaletteColorKey } from '@/config/features';
import {
getAllFeatureKeys,
getDefaultPageOrder,
@@ -43,12 +29,18 @@ import {
import GlobalSnackbar, { useSnackbarState } from '@/components/GlobalSnackbar';
import PageErrorBoundary from '@/components/PageErrorBoundary';
import PageHeader from '@/components/PageHeader';
import { useTheme, type PaletteColor, type Theme } from '@mui/material/styles';
import { useTranslation } from 'react-i18next';
import type { PaletteColorKey } from '@/config/features';
const getPaletteColor = (theme: Theme, key: PaletteColorKey): PaletteColor =>
(theme.palette as unknown as Record<string, PaletteColor>)[key];
const PALETTE_COLORS: Record<PaletteColorKey, string> = {
primary: '#1976d2',
success: '#2e7d32',
warning: '#e65100',
error: '#c62828',
secondary: '#9c27b0',
info: '#0288d1',
};
const getColorCode = (key: PaletteColorKey): string => PALETTE_COLORS[key];
const isValidPage = (page: unknown): page is PageType => {
return typeof page === 'string' && (getAllFeatureKeys() as string[]).includes(page);
@@ -75,7 +67,6 @@ function SortableFeatureRow({
isDisabled,
onToggle,
}: SortableFeatureRowProps) {
const theme = useTheme();
const { t } = useTranslation(['features']);
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: pageKey,
@@ -85,131 +76,85 @@ function SortableFeatureRow({
if (!feature) return null;
const colorKey = feature.themeColorKey ?? 'primary';
const colorCode = getPaletteColor(theme, colorKey).main;
const colorCode = getColorCode(colorKey);
const style = {
transform: CSS.Transform.toString(transform),
transition,
zIndex: isDragging ? 1 : 'auto',
position: 'relative' as const,
backgroundColor: isDragging ? `${colorCode}0a` : 'transparent',
boxShadow: isDragging ? '0 8px 20px rgba(0,0,0,0.08)' : 'none',
};
return (
<Box
<div
ref={setNodeRef}
style={style}
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
p: { xs: 2, sm: 2.5 },
borderBottom: isLast ? 'none' : '1px solid',
borderColor: 'divider',
bgcolor: isDragging ? alpha(colorCode, 0.04) : 'transparent',
boxShadow: isDragging ? `0 8px 20px ${alpha('#000', 0.08)}` : 'none',
transition: 'background-color 0.2s, box-shadow 0.2s',
'&:hover': {
bgcolor: alpha(colorCode, 0.02),
},
'&:hover .drag-handle': {
color: 'text.secondary',
},
}}
className={`flex items-center justify-between p-4 sm:p-5 transition-all duration-200 hover:bg-muted ${
isLast ? '' : 'border-b border-border'
}`}
>
<Stack
direction="row"
spacing={{ xs: 1.5, sm: 2 }}
alignItems="center"
sx={{ flex: 1, minWidth: 0 }}
>
{/* 拖拽手柄 - 整行可拖,手柄是视觉暗示 */}
<Box
className="drag-handle"
<div className="flex items-center gap-3 sm:gap-4 flex-1 min-w-0">
{/* 拖拽手柄 */}
<div
className="drag-handle text-muted-foreground cursor-grab touch-none transition-colors duration-200 hover:text-foreground active:cursor-grabbing"
{...attributes}
{...listeners}
sx={{
color: alpha(theme.palette.text.primary, 0.2),
display: 'flex',
cursor: 'grab',
touchAction: 'none',
transition: 'color 0.2s',
'&:active': { cursor: 'grabbing' },
'&:hover': { color: 'text.secondary' },
}}
aria-label={`拖拽以调整 ${t(feature.labelKey)} 的位置`}
>
<DragIndicatorIcon fontSize="small" />
</Box>
<GripVertical size={16} />
</div>
{/* 功能图标 */}
<Box
sx={{
width: 36,
height: 36,
borderRadius: 2.5,
bgcolor: alpha(colorCode, 0.1),
<div
className="flex items-center justify-center w-9 h-9 rounded-xl flex-shrink-0"
style={{
backgroundColor: `${colorCode}1a`,
color: colorCode,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
{feature.icon && <feature.icon sx={{ fontSize: 20 }} />}
</Box>
{feature.icon && <feature.icon size={20} />}
</div>
{/* 文本信息 */}
<Box sx={{ minWidth: 0, flex: 1 }}>
<Typography
variant="subtitle2"
sx={{
fontWeight: 700,
color: 'text.primary',
fontSize: '0.95rem',
lineHeight: 1.3,
}}
>
<div className="min-w-0 flex-1">
<div className="font-bold text-[0.95rem] leading-tight text-foreground">
{t(feature.labelKey)}
</Typography>
</div>
{feature.descriptionKey && (
<Tooltip title={t(feature.descriptionKey)} placement="top-start" enterDelay={400}>
<Typography
variant="caption"
color="text.secondary"
sx={{
fontWeight: 500,
mt: 0.25,
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 1,
overflow: 'hidden',
textOverflow: 'ellipsis',
wordBreak: 'break-word',
}}
>
{t(feature.descriptionKey)}
</Typography>
</Tooltip>
<div
className="text-xs text-muted-foreground font-medium mt-0.5 overflow-hidden text-ellipsis whitespace-nowrap"
title={t(feature.descriptionKey)}
>
{t(feature.descriptionKey)}
</div>
)}
</Box>
</Stack>
</div>
</div>
<Switch
color="primary"
checked={isChecked}
onChange={() => onToggle(pageKey)}
{/* 开关 */}
<button
type="button"
role="switch"
aria-checked={isChecked}
disabled={isDisabled}
/>
</Box>
onClick={() => onToggle(pageKey)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${
isChecked ? 'bg-primary' : 'bg-muted'
} ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-background transition-transform duration-200 ${
isChecked ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
);
}
/**
* Options 设置页面主组件
* 支持对不同窗口入口的功能显示和排序进行独立配置
*/
export default function App() {
const theme = useTheme();
const { t } = useTranslation(['features', 'common']);
const initialWindowType = useMemo(() => {
@@ -360,120 +305,63 @@ export default function App() {
if (!isLoaded) {
return (
<Box
sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}
>
<CircularProgress size={24} />
</Box>
<div className="flex justify-center items-center min-h-screen">
<div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div>
);
}
return (
<Box
className="app"
sx={{
minHeight: '100vh',
bgcolor: 'background.default',
display: 'flex',
flexDirection: 'column',
}}
>
<div className="app min-h-screen bg-background flex flex-col">
<PageErrorBoundary>
{/* 顶部标题与导航栏 */}
<Box
sx={{
width: '100%',
bgcolor: 'background.paper',
borderBottom: '1px solid',
borderColor: 'divider',
pt: { xs: 3, sm: 5 },
pb: 0,
px: { xs: 2, sm: 4 },
}}
>
<Box sx={{ maxWidth: 800, mx: 'auto' }}>
<div className="w-full bg-background border-b border-border pt-8 sm:pt-12 pb-0 px-4 sm:px-8">
<div className="max-w-3xl mx-auto">
<PageHeader
icon={<SettingsIcon />}
iconColor={theme.palette.primary.main}
icon={<Settings size={20} />}
iconColor="#1976d2"
title="应用设置"
subtitle="针对不同窗口类型独立配置 Dashboard 中显示的功能及其排序"
sx={{ mb: 4 }}
/>
{/* Tab 与恢复按钮同行 */}
<Stack
direction="row"
alignItems="flex-end"
justifyContent="space-between"
sx={{ borderBottom: 'none' }}
>
<Tabs
value={windowType}
onChange={handleWindowTypeChange}
indicatorColor="primary"
textColor="primary"
sx={{
flex: 1,
minHeight: 'auto',
'& .MuiTab-root': {
fontWeight: 700,
fontSize: '0.9rem',
textTransform: 'none',
minWidth: { xs: 100, sm: 140 },
letterSpacing: '0.3px',
},
'& .MuiTabs-indicator': {
height: 3,
borderRadius: '3px 3px 0 0',
},
}}
<div className="flex items-end justify-between border-b-0">
<div className="flex-1 flex">
{(['popup', 'sidepanel', 'tab'] as WindowType[]).map((type) => (
<button
key={type}
onClick={(e) => handleWindowTypeChange(e, type)}
className={`px-4 sm:px-6 py-2 text-[0.9rem] font-bold transition-colors duration-200 ${
windowType === type
? 'text-primary border-b-2 border-primary'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{type === 'popup' ? 'Popup 窗口' : type === 'sidepanel' ? '侧边栏' : '标签页'}
</button>
))}
</div>
<button
onClick={handleRestoreDefaults}
className="mb-1 ml-2 p-1.5 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-lg transition-colors duration-200"
title="恢复当前模式默认"
>
<Tab value="popup" label="Popup 窗口" />
<Tab value="sidepanel" label="侧边栏" />
<Tab value="tab" label="标签页" />
</Tabs>
<Tooltip title="恢复当前模式默认" placement="top">
<IconButton
onClick={handleRestoreDefaults}
size="small"
sx={{
mb: 1,
ml: 1,
color: 'text.secondary',
'&:hover': {
color: 'primary.main',
bgcolor: alpha(theme.palette.primary.main, 0.08),
},
}}
aria-label="恢复当前模式默认"
>
<RefreshIcon fontSize="small" />
</IconButton>
</Tooltip>
</Stack>
</Box>
</Box>
<RefreshCw size={16} />
</button>
</div>
</div>
</div>
{/* 主内容区域 */}
<Box sx={{ flex: 1, p: { xs: 2, sm: 4 } }}>
<Box sx={{ maxWidth: 800, mx: 'auto' }}>
<Paper
elevation={0}
sx={{
borderRadius: 4,
border: '1px solid',
borderColor: 'divider',
overflow: 'hidden',
bgcolor: 'background.paper',
boxShadow: '0 4px 24px rgba(0,0,0,0.03)',
}}
>
<div className="flex-1 p-4 sm:p-8">
<div className="max-w-3xl mx-auto">
<div className="rounded-2xl border border-border overflow-hidden bg-card shadow-sm">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext items={pageOrder} strategy={verticalListSortingStrategy}>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<div className="flex flex-col">
{pageOrder.map((key, index, array) => {
const isChecked = visiblePages.includes(key);
const isDisabled = isChecked && visiblePages.length === 1;
@@ -488,15 +376,15 @@ export default function App() {
/>
);
})}
</Box>
</div>
</SortableContext>
</DndContext>
</Paper>
</Box>
</Box>
</div>
</div>
</div>
</PageErrorBoundary>
<GlobalSnackbar {...snackbarProps} />
</Box>
</div>
);
}
+1
View File
@@ -1,6 +1,7 @@
import ReactDOM from 'react-dom/client';
import AppRoot from '@/providers/AppRoot';
import '@/i18n';
import '@/src/index.css';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
+2 -25
View File
@@ -3,12 +3,10 @@ import TopBar from '@/components/TopBar';
import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary';
import { SnackbarProvider } from '@/components/GlobalSnackbar';
import { Box } from '@mui/material';
import { getEntryPointType } from '@/config/features';
import { useMemo } from 'react';
export default function App() {
// 打开Chrome扩展选项页面,需确保manifest中已配置options_page或options_ui
const handleOpenOptions = () => {
chrome.runtime.openOptionsPage().catch(console.error);
};
@@ -37,33 +35,12 @@ export default function App() {
pageOrderKey={routerConfig.pageOrderKey}
>
<SnackbarProvider initialOptions={{ autoHideDuration: 1500 }}>
<Box
className="app"
sx={{
display: 'flex',
flexDirection: 'column',
width: '400px',
maxWidth: '400px',
minWidth: '400px',
height: '600px',
minHeight: '600px',
overflow: 'hidden',
backgroundColor: 'background.default',
// 仅在明确的大屏幕(如独立页面或侧边栏拉伸)下才允许扩展
'@media screen and (min-width: 600px)': {
width: '100vw',
maxWidth: 'none',
minWidth: 'none',
height: '100vh',
minHeight: 'none',
},
}}
>
<div className="app flex flex-col w-[400px] max-w-[400px] min-w-[400px] h-[600px] min-h-[600px] overflow-hidden bg-background sm:w-screen sm:max-w-none sm:min-w-0 sm:h-screen sm:min-h-0">
<TopBar onOpenOptions={handleOpenOptions} />
<ErrorBoundary>
<RouterContainer />
</ErrorBoundary>
</Box>
</div>
</SnackbarProvider>
</RouterProvider>
);
+1 -1
View File
@@ -13,7 +13,7 @@
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f5f5f5; /* Light mode default */
background-color: hsl(var(--background));
}
/* Ensure full size for the root container */
#root {
+1
View File
@@ -1,6 +1,7 @@
import ReactDOM from 'react-dom/client';
import AppRoot from '@/providers/AppRoot';
import '@/i18n';
import '@/src/index.css';
import App from './App.tsx';
ReactDOM.createRoot(document.getElementById('root')!).render(
+2 -14
View File
@@ -5,7 +5,6 @@ import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary';
import { SnackbarProvider } from '@/components/GlobalSnackbar';
import { MessageAction, sendMessage } from '@/utils/messages';
import { Box } from '@mui/material';
export default function App() {
const handleOpenOptions = () => {
@@ -14,11 +13,9 @@ export default function App() {
});
};
// 通知侧边栏已打开
useEffect(() => {
sendMessage(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: true });
return () => {
// 尝试在关闭时通知,虽然在某些情况下可能无法成功发送
sendMessage(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: false });
};
}, []);
@@ -26,21 +23,12 @@ export default function App() {
return (
<RouterProvider defaultRoute="dashboard" syncKey="app/sidepanelRoute">
<SnackbarProvider initialOptions={{ autoHideDuration: 1500 }}>
<Box
className="app"
sx={{
display: 'flex',
flexDirection: 'column',
height: '100vh',
width: '100%',
overflow: 'hidden',
}}
>
<div className="app flex flex-col h-screen w-full overflow-hidden">
<TopBar onOpenOptions={handleOpenOptions} />
<ErrorBoundary>
<RouterContainer />
</ErrorBoundary>
</Box>
</div>
</SnackbarProvider>
</RouterProvider>
);
+1
View File
@@ -1,6 +1,7 @@
import ReactDOM from 'react-dom/client';
import AppRoot from '@/providers/AppRoot';
import '@/i18n';
import '@/src/index.css';
import App from './App.tsx';
ReactDOM.createRoot(document.getElementById('root')!).render(