Compare commits

...

8 Commits

Author SHA1 Message Date
rsgltzyd 06c2a222ab 重构导航逻辑,去除dashboard页面相关功能,增加侧边栏导航功能 2026-07-05 22:34:12 +08:00
rsgltzyd b487f71512 refactor: 移除 TopBar 组件,重构功能导航并引入主题切换按钮
- 删除 TopBar 及其相关组件和逻辑,简化布局结构。
- 新增 FeatureNav 组件,包含功能导航和主题切换按钮。
- 更新 README.md,反映新的组件结构和功能。
- 修改测试用例,确保新结构下的功能正常。
2026-07-05 22:30:13 +08:00
rsgltzyd 43038c5edb refactor: 更新 RouterProvider 以过滤非法页面并合并配置 2026-07-05 22:20:04 +08:00
rsgltzyd 9aa7a51f0b refactor: 移除 Dashboard 页面及相关功能,更新路由和组件逻辑
- 移除 Dashboard 相关的组件、特性和测试代码,简化项目结构。
- 更新 PageSkeleton 组件,默认渲染工具页面骨架。
- 修改 RouterContainer 和 RouterProvider 以适应新的默认路由策略,确保用户直接访问 timestamp 页面。
- 更新测试用例,确保在新结构下的功能正常。
2026-07-05 22:02:25 +08:00
rsgltzyd d21e970f56 feat: 重构 Popup 布局,移除 Dashboard 页面并引入功能导航
- 更新 README.md,添加 Popup 功能导航文档链接。
- 新建 feature-nav-layout.md,详细描述 Popup 布局重构的背景、目标及设计。
- 移除 Dashboard 相关代码,更新 RouterProvider 和 TopBar 以适应新布局。
- 修改默认路由策略,确保新用户直接访问 timestamp 页面。
2026-07-05 21:55:22 +08:00
rsgltzyd 6589ea3858 refactor: 移除侧边栏相关功能和代码 2026-07-05 21:47:35 +08:00
rsgltzyd 1af3b25af8 Merge branch 'develop' 2026-07-05 21:39:32 +08:00
rsgltzyd 6be9b31ca2 docs: 将spec目录移动到docs目录中 2026-07-05 21:34:41 +08:00
54 changed files with 774 additions and 1328 deletions
+1
View File
@@ -5,3 +5,4 @@
| 文档 | 状态 | 说明 | | 文档 | 状态 | 说明 |
| -------------------------------------------------------------------------------- | ----------------- | ---------------------------------------------------- | | -------------------------------------------------------------------------------- | ----------------- | ---------------------------------------------------- |
| [storage-cleaner/indexeddb-fix-plan.md](./storage-cleaner/indexeddb-fix-plan.md) | ✅ Phase 3 已完成 | Storage Cleaner IndexedDB 清理逻辑修复方案与验收标准 | | [storage-cleaner/indexeddb-fix-plan.md](./storage-cleaner/indexeddb-fix-plan.md) | ✅ Phase 3 已完成 | Storage Cleaner IndexedDB 清理逻辑修复方案与验收标准 |
| [popup-layout/feature-nav-layout.md](./popup-layout/feature-nav-layout.md) | 待实施 | Popup 右侧图标导航、移除 Dashboard、默认 timestamp |
@@ -0,0 +1,356 @@
# Popup 布局重构 — 功能导航与 Dashboard 移除
> 创建时间: 2026-07-05
> 状态: 待实施
> 关联模块: `src/entrypoints/popup/`、`src/layout/FeatureNav/`、`src/providers/RouterProvider.tsx`
> 影响范围: 仅 popup 入口(tab / sidepanel 不在本次布局范围)
## 背景与目标
当前 popup 采用 **Dashboard 首页 + TopBar 搜索跳转** 模式:用户打开扩展后先看到仪表盘卡片网格,再点击进入具体工具。布局为固定 400×600(见 `src/entrypoints/popup/App.tsx``src/entrypoints/popup/index.html`),TopBar 在非 dashboard 页面显示「返回首页」按钮。
该模式增加了一步选工具操作。本次重构将 popup 改为 **工具直达 + 右侧常驻导航**,并移除 Dashboard 页面。
| 维度 | 现状 | 目标 |
| ---------- | ----------------------------- | ----------------------------------------- |
| 默认页 | `dashboard` | 新用户默认 `timestamp` |
| 导航 | Dashboard 卡片网格 + 搜索跳转 | 右侧常驻纯图标导航栏 |
| 首页 | Dashboard 独立页 | 移除 |
| Popup 宽度 | 400px | 450px(内容区 ~402px + 导航栏 48px |
| 作用范围 | — | 仅 popup 改布局;tab / sidepanel 不加导航 |
---
## 布局设计
### 结构示意
```mermaid
flowchart LR
subgraph popup ["Popup 450x600"]
subgraph mainCol ["主列 flex-1"]
TopBar["TopBar"]
Content["RouterContainer"]
TopBar --> Content
end
NavCol["FeatureNav 48px"]
end
mainCol --- NavCol
```
### 尺寸约束
| 属性 | 值 | 说明 |
| -------- | ------ | ---------------------------------------------- |
| 总宽度 | 450px | `App.tsx` 容器 + `index.html` 内联样式同步修改 |
| 总高度 | 600px | 不变 |
| 主内容列 | flex-1 | 约 402px,需 `min-w-0` 防止 flex 子项溢出 |
| 导航栏 | 48px | Tailwind `w-12`,固定宽度,不参与 flex 收缩 |
### 视觉规范
- 导航栏:左侧 `border-l border-border`,垂直排列图标按钮
- 图标按钮:`h-9 w-9``h-10 w-10`,纯图标
- Tooltip:使用原生 `title` 属性 + `aria-label={feature.label}`,不引入 Tooltip 组件
- Active 态:背景 `bg-muted` + 左侧 `border-l-2 border-primary`
- 导航列表超出高度时:`overflow-y-auto`(600px 高度下 9 个工具通常无需滚动)
---
## FeatureNav 组件规格
新建 `src/layout/FeatureNav/`,遵循 UI + Hook 分离模式(见 `.github/CODING_STANDARDS.md` §11)。
### 文件结构
```
src/layout/FeatureNav/
├── index.tsx # 垂直图标按钮列表、active 高亮、无障碍属性
├── useFeatureNav.ts # 读路由状态,暴露 navItems / navigateTo / currentPage
├── resolveNavFeatures.ts # 从 Dashboard 迁出的功能列表解析逻辑
└── __tests__/
├── index.test.tsx
└── resolveNavFeatures.test.ts
```
### resolveNavFeatures.ts
`src/pages/Dashboard/dashboardFeatures.ts` 迁出并重命名:
```typescript
export interface NavFeatureItem {
key: PageType;
feature: FeatureConfig & { icon: NonNullable<FeatureConfig['icon']> };
}
export function resolveNavFeatures(keys: PageType[], visiblePages: PageType[]): NavFeatureItem[];
```
逻辑与旧 `resolveDashboardFeatures` 一致:
-`keys`(即 `pageOrder`)顺序遍历
- 跳过不在 `visiblePages` 中的项
- 跳过无 `icon` 的 featuredashboard 移除后不应出现)
### useFeatureNav.ts
```typescript
export interface UseFeatureNavReturn {
navItems: NavFeatureItem[];
currentPage: PageType;
navigateTo: (page: PageType) => void;
}
```
-`useRouter()` 读取 `currentPage``pageOrder``visiblePages``navigateTo`
-`useMemo` 调用 `resolveNavFeatures(pageOrder, visiblePages)` 生成 `navItems`
### index.tsx
- 渲染 `<nav aria-label="功能导航">` 包裹垂直按钮列表
- 每项为 `<button type="button">`,内含 Lucide 图标
- 点击调用 `navigateTo(item.key)`
- 当前项添加 active 样式与 `aria-current="page"`
### 引用范围
**仅** `src/entrypoints/popup/App.tsx` 引用 `FeatureNav`。sidepanel / tab 入口不引入该组件。
---
## popup/App.tsx 目标结构
```tsx
import RouterProvider from '@/providers/RouterProvider';
import TopBar from '@/layout/TopBar';
import FeatureNav from '@/layout/FeatureNav';
import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary';
export default function App() {
return (
<RouterProvider
defaultRoute="timestamp"
syncKey="app/popupRoute"
visiblePagesKey="app/popupVisiblePages"
pageOrderKey="app/popupPageOrder"
>
<div className="flex w-[450px] max-w-[450px] min-w-[450px] h-[600px] min-h-[600px] overflow-hidden bg-background">
<div className="flex flex-col flex-1 min-w-0">
<TopBar />
<ErrorBoundary>
<RouterContainer />
</ErrorBoundary>
</div>
<FeatureNav />
</div>
</RouterProvider>
);
}
```
`src/entrypoints/popup/index.html` 内联样式中 `width: 400px` 改为 `width: 450px`
---
## 移除 Dashboard(全局类型变更)
布局仅改 popup,但 `dashboard``PageType` 移除会影响全项目类型与路由校验。
### 删除文件
| 路径 | 说明 |
| ------------------------------------- | ---------------- |
| `src/pages/Dashboard/` | 整目录(含测试) |
| `src/config/pageLoaders/dashboard.ts` | Dashboard 懒加载 |
### 修改文件
| 文件 | 改动 |
| ------------------------------------ | ----------------------------------------------------------- |
| `src/types/storage.d.ts` | 从 `PageType` 联合类型删除 `'dashboard'` |
| `src/config/featureMeta.ts` | 删除 dashboard 条目 |
| `src/config/pageLoaders/index.ts` | 删除 `case 'dashboard'` |
| `src/components/RouterContainer.tsx` | 去掉 dashboard 骨架屏分支;统一使用 `page-transition-enter` |
| `src/components/PageSkeleton.tsx` | 删除 `variant: 'dashboard'` 及对应 UI |
| `src/styles/shell.css` | 删除 `.page-transition-dashboard` |
### TopBar 精简
`src/layout/TopBar/index.tsx``useTopBar.ts`
- 删除「返回首页」按钮(`ArrowLeft` + `goHome`
- 删除 `isDashboard` 状态及相关导出
- 搜索过滤中 `f.key === 'dashboard'` 的特殊排除逻辑可删除
### RouterProvider 变更
`src/providers/RouterProvider.tsx`
- 删除 `goHome()` 方法及 Context 中的 `goHome` 字段
- 全局 `defaultRoute` 默认值由 `'dashboard'` 改为 `'timestamp'`
- popup 显式传入 `defaultRoute="timestamp"`(与全局默认一致,便于阅读)
### Sidepanel 最小修复
`src/entrypoints/sidepanel/App.tsx` 若仍存在:
- `defaultRoute="dashboard"` 改为 `defaultRoute="timestamp"`
- 不添加 FeatureNav 布局
---
## 默认路由策略(仅新用户)
利用现有 `RouterProvider` 机制,**无需额外迁移代码**。
```typescript
// 首屏(localStorage 快照,消除闪烁)
const [currentPage] = useState(() => getSyncSnapshot(syncKey, defaultRoute, isValidPage));
// 异步加载 chrome.storage
const savedRoute = (stored[syncKey] ?? defaultRoute) as PageType;
if (isValidPage(savedRoute) && syncRoute && !hasUserNavigatedRef.current) {
setCurrentPage(savedRoute);
}
```
| 场景 | 行为 |
| ------------------------------------------ | ---------------------------------------------------------------- |
| 新用户(无 `app/popupRoute`) | 首屏 + 持久化均为 `timestamp` |
| 老用户(如 `app/popupRoute: 'jsonTools'`) | 恢复上次路由 |
| 老用户曾存 `dashboard` | `isValidPage('dashboard')` 为 false → 回退 `timestamp`(软迁移) |
| 右键菜单 deep link | `?feature=&payload=` 优先级不变,高于默认路由 |
| 用户主动切换 | `navigateTo``hasUserNavigatedRef` 阻止异步覆盖 |
`visiblePages` / `pageOrder` 中残留的 `dashboard``mergeWithDefaults` 自动滤除(不在新默认列表中)。
### 边界说明
`recentlyUsedTools` 若含已移除的 `dashboard` 等非法项,当前 `isValidPageList` 校验要求数组**全部**合法,失败时整表回退为 `[]`。影响:TopBar 搜索历史中的「最近使用」可能被清空。此为已知低影响边界;实现时可选优化为「过滤非法项保留合法项」,**非必须**。
---
## 实施顺序
```
1. 迁出 resolveNavFeatures + 新建 FeatureNav 组件与测试
2. 修改 popup/App.tsx 布局 + popup/index.html 宽度
3. 全局移除 dashboardPageType → FEATURES → pageLoader → 删页面目录)
4. 精简 TopBar / RouterProvider / RouterContainer / PageSkeleton
5. 批量更新测试 → npm run typecheck && npm run test && npm run lint
```
---
## 验收标准
### A. 布局与导航(手动)
| 编号 | 步骤 | 期望 |
| ---- | ------------------------------------ | ---------------------------------------------- |
| A-1 | 首次安装(或清空 storage)打开 popup | 默认显示时间戳页,右侧导航 timestamp 项高亮 |
| A-2 | 依次点击各导航图标 | 切换到对应工具页,active 态跟随当前页 |
| A-3 | hover 各导航图标 | 显示中文功能名 tooltip(`title` 属性) |
| A-4 | 使用过某工具后关闭再打开 popup | 恢复上次路由(非 dashboard |
| A-5 | 检查 popup 尺寸 | 宽度 450px,高度 600px,内容区不被导航挤压溢出 |
### B. Dashboard 移除
| 编号 | 期望 |
| ---- | -------------------------------------------------------------------- |
| B-1 | TopBar 搜索下拉无 dashboard 项 |
| B-2 | TopBar 无「返回首页」按钮 |
| B-3 | `PageType``FEATURES``loadPage` 中无 dashboard |
| B-4 | storage 中 `app/popupRoute: 'dashboard'` 时打开 popup 落到 timestamp |
| B-5 | `visiblePages` 含 dashboard 时自动滤除,导航正常显示工具列表 |
### C. 单元测试
| 编号 | 覆盖 |
| ---- | -------------------------------------------------------------------------- |
| C-1 | `FeatureNav` 渲染全部可见工具图标 |
| C-2 | `FeatureNav` 点击图标调用 `navigateTo` |
| C-3 | `FeatureNav` 当前页对应项有 active 样式 / `aria-current` |
| C-4 | `resolveNavFeatures` 按 pageOrder 排序、respect visiblePages |
| C-5 | 更新 `RouterProvider` / `TopBar` / `RouterContainer` / `features` 相关测试 |
| C-6 | 删除 `src/pages/Dashboard/__tests__/` 下全部测试 |
### D. CI
| 编号 | 标准 |
| ---- | ------------------------ |
| D-1 | `npm run typecheck` 通过 |
| D-2 | `npm run test` 通过 |
| D-3 | `npm run lint` 通过 |
---
## 不在范围
- tab / sidepanel 布局改造(不加 FeatureNav
- `visiblePages` / `pageOrder` 可视化配置 UI
- Popup 高度变更(保持 600px
- 修改 `AGENTS.md` 中 spec 目录引用(实际 spec 位于 `docs/spec/`
---
## PR 检查清单
```markdown
## 功能
- [ ] 新建 FeatureNav 组件(index / useFeatureNav / resolveNavFeatures
- [ ] popup 布局改为双列(主内容 + 右侧导航)
- [ ] popup 宽度 450pxApp.tsx + index.html
- [ ] popup defaultRoute="timestamp"
- [ ] 全局移除 dashboardPageType、FEATURES、pageLoader、页面目录)
- [ ] TopBar 移除返回按钮与 goHome 相关逻辑
- [ ] RouterProvider 移除 goHomedefaultRoute 改为 timestamp
- [ ] sidepanel defaultRoute 最小修复(若文件存在)
## 测试
- [ ] FeatureNav / resolveNavFeatures 单元测试
- [ ] 更新 RouterProvider / TopBar / RouterContainer / features 测试
- [ ] 删除 Dashboard 相关测试
## 验收
- [ ] npm run typecheck / test / lint 通过
- [ ] 手动 A-1 ~ A-5、B-1 ~ B-4 通过
```
---
## 风险与边界说明
1. **Dashboard 移除为全局变更**:虽 FeatureNav 仅 popup 使用,但 `PageType` 删除 `dashboard` 会影响所有入口的类型校验与路由合法性。
2. **老用户 dashboard 路由软迁移**:依赖 `isValidPage` 回退到 `defaultRoute`,不会 crash,但用户会察觉「首页消失、默认变为时间戳」——符合预期。
3. **450px 宽度**Chrome popup 允许扩展较默认更宽;若未来 Firefox 有差异需在 Firefox 构建中手动验证。
4. **recentlyUsedTools 整表校验**:见「默认路由策略 → 边界说明」,可选后续优化。
---
## 相关文件索引
| 文件 | 说明 |
| ------------------------------------- | ------------------------------- |
| `src/entrypoints/popup/App.tsx` | popup 布局入口,引用 FeatureNav |
| `src/entrypoints/popup/index.html` | popup 初始尺寸 450px |
| `src/layout/FeatureNav/` | 新建:右侧图标导航 |
| `src/layout/TopBar/` | 精简:移除返回按钮 |
| `src/providers/RouterProvider.tsx` | 默认路由、移除 goHome |
| `src/config/featureMeta.ts` | FEATURES 定义,删除 dashboard |
| `src/types/storage.d.ts` | PageType 定义 |
| `src/config/pageLoaders/index.ts` | 页面懒加载路由 |
| `src/components/RouterContainer.tsx` | 页面渲染容器 |
| `src/components/PageSkeleton.tsx` | 加载骨架屏 |
| `src/styles/shell.css` | 页面过渡动画 |
| `src/pages/Dashboard/` | **删除** |
| `src/config/pageLoaders/dashboard.ts` | **删除** |
| `src/entrypoints/sidepanel/App.tsx` | 最小修复 defaultRoute |
---
> **注**:项目 spec 文档实际目录为 `docs/spec/`。`AGENTS.md` 中引用的根目录 `spec/README.md` 尚未建立,以本目录 [`README.md`](../README.md) 为索引。
+1 -38
View File
@@ -4,30 +4,6 @@
* 用于 Suspense fallback 和初始加载状态,提供平滑的视觉过渡 * 用于 Suspense fallback 和初始加载状态,提供平滑的视觉过渡
* 避免白屏闪烁,减少布局偏移 * 避免白屏闪烁,减少布局偏移
*/ */
interface PageSkeletonProps {
/** 骨架屏类型 */
variant?: 'dashboard' | 'tool';
}
/**
* 仪表盘卡片骨架屏
*/
function DashboardCardSkeleton() {
return (
<div className="rounded-xl border border-border p-5 h-[100px]">
<div className="flex justify-between items-start">
<div className="flex gap-3 items-center">
<div className="w-10 h-10 rounded-lg bg-muted animate-pulse" />
<div>
<div className="w-24 h-5 bg-muted rounded animate-pulse" />
<div className="w-32 h-3.5 bg-muted rounded animate-pulse mt-1.5" />
</div>
</div>
<div className="w-3 h-3 rounded-full bg-muted animate-pulse" />
</div>
</div>
);
}
/** /**
* 工具页面骨架屏 * 工具页面骨架屏
@@ -57,22 +33,9 @@ function ToolPageSkeleton() {
/** /**
* 页面加载骨架屏 * 页面加载骨架屏
*
* @param props - PageSkeletonProps
* @returns 骨架屏 JSX 元素
*/ */
export default function PageSkeleton({ variant = 'dashboard' }: PageSkeletonProps) { export default function PageSkeleton() {
if (variant === 'tool') {
return <ToolPageSkeleton />; return <ToolPageSkeleton />;
} }
return (
<div className="grid grid-cols-1 sm:grid-cols-[repeat(auto-fill,minmax(300px,1fr))] auto-rows-fr gap-4 p-4">
{Array.from({ length: 6 }).map((_, index) => (
<DashboardCardSkeleton key={index} />
))}
</div>
);
}
PageSkeleton.displayName = 'PageSkeleton'; PageSkeleton.displayName = 'PageSkeleton';
+2 -6
View File
@@ -30,7 +30,7 @@ function LoadedPage({ pageKey }: { pageKey: PageType }) {
}, [pageKey]); }, [pageKey]);
if (!Page) { if (!Page) {
return <PageSkeleton variant={pageKey === 'dashboard' ? 'dashboard' : 'tool'} />; return <PageSkeleton />;
} }
return <Page />; return <Page />;
@@ -39,9 +39,6 @@ function LoadedPage({ pageKey }: { pageKey: PageType }) {
export default function RouterContainer() { export default function RouterContainer() {
const { currentPage } = useRouter(); const { currentPage } = useRouter();
const animationClass =
currentPage === 'dashboard' ? 'page-transition-dashboard' : 'page-transition-enter';
const currentFeature = getFeatureByKey(currentPage); const currentFeature = getFeatureByKey(currentPage);
return ( return (
@@ -49,8 +46,7 @@ export default function RouterContainer() {
key={currentPage} key={currentPage}
className={cn( className={cn(
'flex-1 flex flex-col overflow-x-hidden overflow-y-auto', 'flex-1 flex flex-col overflow-x-hidden overflow-y-auto',
'motion-reduce:transition-none', 'motion-reduce:transition-none page-transition-enter',
animationClass,
)} )}
> >
<PageErrorBoundary resetKey={currentPage}> <PageErrorBoundary resetKey={currentPage}>
+5 -37
View File
@@ -4,41 +4,17 @@ import PageSkeleton from '@/components/PageSkeleton';
describe('PageSkeleton 组件', () => { describe('PageSkeleton 组件', () => {
describe('渲染测试', () => { describe('渲染测试', () => {
it('默认应渲染 dashboard 骨架', () => { it('应渲染工具页面骨架', () => {
const { container } = render(<PageSkeleton />); const { container } = render(<PageSkeleton />);
// dashboard 骨架屏包含 6 个卡片
const cards = container.querySelectorAll('.rounded-xl');
expect(cards.length).toBe(6);
});
it('variant 为 dashboard 时应渲染仪表盘卡片骨架', () => {
const { container } = render(<PageSkeleton variant="dashboard" />);
// 每个卡片有 2 个骨架元素(图标、文本),6 个卡片共 12 个
const cards = container.querySelectorAll('.rounded-xl');
expect(cards.length).toBe(6);
});
it('variant 为 tool 时应渲染工具页面骨架', () => {
const { container } = render(<PageSkeleton variant="tool" />);
// tool 骨架屏包含标题、输入区、控制栏 3 个按钮、结果区
const skeletons = container.querySelectorAll('.animate-pulse'); const skeletons = container.querySelectorAll('.animate-pulse');
expect(skeletons.length).toBeGreaterThan(0); expect(skeletons.length).toBeGreaterThan(0);
}); });
}); });
describe('布局结构测试', () => { describe('布局结构测试', () => {
it('dashboard 骨架屏应使用 grid 布局', () => { it('工具骨架屏应有内边距', () => {
const { container } = render(<PageSkeleton variant="dashboard" />); const { container } = render(<PageSkeleton />);
const gridContainer = container.firstChild as HTMLElement;
expect(gridContainer).toHaveClass('grid');
});
it('tool 骨架屏应有内边距', () => {
const { container } = render(<PageSkeleton variant="tool" />);
const toolContainer = container.firstChild as HTMLElement; const toolContainer = container.firstChild as HTMLElement;
expect(toolContainer).toHaveClass('p-5'); expect(toolContainer).toHaveClass('p-5');
@@ -46,16 +22,8 @@ describe('PageSkeleton 组件', () => {
}); });
describe('骨架屏元素测试', () => { describe('骨架屏元素测试', () => {
it('dashboard 骨架屏应包含圆角和边框样式', () => { it('工具骨架屏应包含动画脉冲效果', () => {
const { container } = render(<PageSkeleton variant="dashboard" />); const { container } = render(<PageSkeleton />);
// 获取第一个卡片容器
const card = container.querySelector('.rounded-xl.border');
expect(card).toBeInTheDocument();
});
it('tool 骨架屏应包含动画脉冲效果', () => {
const { container } = render(<PageSkeleton variant="tool" />);
const skeletons = container.querySelectorAll('.animate-pulse'); const skeletons = container.querySelectorAll('.animate-pulse');
expect(skeletons.length).toBeGreaterThan(0); expect(skeletons.length).toBeGreaterThan(0);
@@ -6,12 +6,10 @@ import type { PageType } from '@/types/storage';
import React from 'react'; import React from 'react';
const mockRouterValue = { const mockRouterValue = {
currentPage: 'dashboard' as PageType, currentPage: 'timestamp' as PageType,
visiblePages: ['dashboard', 'timestamp'] as PageType[], visiblePages: ['timestamp', 'jwt'] as PageType[],
pageOrder: ['timestamp'] as PageType[], pageOrder: ['timestamp'] as PageType[],
navigateTo: vi.fn(), navigateTo: vi.fn(),
syncNavigation: vi.fn(),
goHome: vi.fn(),
setVisiblePages: vi.fn(), setVisiblePages: vi.fn(),
setPageOrder: vi.fn(), setPageOrder: vi.fn(),
recentlyUsedTools: [] as PageType[], recentlyUsedTools: [] as PageType[],
@@ -34,21 +32,14 @@ describe('RouterContainer 组件', () => {
describe('渲染测试', () => { describe('渲染测试', () => {
it('mount 后应直接渲染页面结构(不等待 storage 加载)', () => { it('mount 后应直接渲染页面结构(不等待 storage 加载)', () => {
mockRouterValue.currentPage = 'dashboard'; mockRouterValue.currentPage = 'timestamp';
const { container } = renderWithProvider(<RouterContainer />); const { container } = renderWithProvider(<RouterContainer />);
expect(container.querySelector('.page-transition-dashboard')).toBeInTheDocument(); expect(container.querySelector('.page-transition-enter')).toBeInTheDocument();
}); });
}); });
describe('动画类测试', () => { describe('动画类测试', () => {
it('在 dashboard 页面应应用 dashboard 动画类', () => { it('应应用 enter 动画类', () => {
mockRouterValue.currentPage = 'dashboard';
renderWithProvider(<RouterContainer />);
const box = document.querySelector('.page-transition-dashboard');
expect(box).toBeInTheDocument();
});
it('在非 dashboard 页面应应用 enter 动画类', () => {
mockRouterValue.currentPage = 'timestamp'; mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<RouterContainer />); renderWithProvider(<RouterContainer />);
const box = document.querySelector('.page-transition-enter'); const box = document.querySelector('.page-transition-enter');
@@ -60,7 +51,7 @@ describe('RouterContainer 组件', () => {
it('currentPage 变化时应更新', () => { it('currentPage 变化时应更新', () => {
const { rerender } = renderWithProvider(<RouterContainer />); const { rerender } = renderWithProvider(<RouterContainer />);
mockRouterValue.currentPage = 'timestamp'; mockRouterValue.currentPage = 'jwt';
rerender(<RouterProvider>{<RouterContainer />}</RouterProvider>); rerender(<RouterProvider>{<RouterContainer />}</RouterProvider>);
const box = document.querySelector('.page-transition-enter'); const box = document.querySelector('.page-transition-enter');
@@ -70,11 +61,10 @@ describe('RouterContainer 组件', () => {
describe('页面级错误隔离', () => { describe('页面级错误隔离', () => {
it('PageErrorBoundary 应包裹页面内容', () => { it('PageErrorBoundary 应包裹页面内容', () => {
mockRouterValue.currentPage = 'dashboard'; mockRouterValue.currentPage = 'timestamp';
const { container } = renderWithProvider(<RouterContainer />); const { container } = renderWithProvider(<RouterContainer />);
// 验证 RouterContainer 的 Box 结构存在 const routerBox = container.querySelector('.page-transition-enter');
const routerBox = container.querySelector('.page-transition-dashboard');
expect(routerBox).toBeInTheDocument(); expect(routerBox).toBeInTheDocument();
}); });
}); });
+5 -9
View File
@@ -4,10 +4,6 @@ const pageLoadTracker = vi.hoisted(() => ({
loaded: [] as string[], loaded: [] as string[],
})); }));
vi.mock('@/pages/Dashboard', () => {
pageLoadTracker.loaded.push('Dashboard');
return { default: () => null };
});
vi.mock('@/pages/Timestamp', () => { vi.mock('@/pages/Timestamp', () => {
pageLoadTracker.loaded.push('Timestamp'); pageLoadTracker.loaded.push('Timestamp');
return { default: () => null }; return { default: () => null };
@@ -63,24 +59,24 @@ describe('features 懒加载', () => {
it('访问 FEATURES 元数据时不应加载任何页面模块', async () => { it('访问 FEATURES 元数据时不应加载任何页面模块', async () => {
const { FEATURES } = await import('@/config/features'); const { FEATURES } = await import('@/config/features');
expect(FEATURES).toHaveLength(10); expect(FEATURES).toHaveLength(9);
expect(pageLoadTracker.loaded).toEqual([]); expect(pageLoadTracker.loaded).toEqual([]);
}); });
it('loadPage 应仅加载对应页面模块', async () => { it('loadPage 应仅加载对应页面模块', async () => {
const { loadPage } = await import('@/config/pageLoaders/index'); const { loadPage } = await import('@/config/pageLoaders/index');
await loadPage('dashboard'); await loadPage('timestamp');
expect(pageLoadTracker.loaded).toEqual(['Dashboard']); expect(pageLoadTracker.loaded).toEqual(['Timestamp']);
}); });
it('loadPage 切换页面时不应加载无关页面模块', async () => { it('loadPage 切换页面时不应加载无关页面模块', async () => {
const { loadPage } = await import('@/config/pageLoaders/index'); const { loadPage } = await import('@/config/pageLoaders/index');
await loadPage('timestamp'); await loadPage('jwt');
expect(pageLoadTracker.loaded).toEqual(['Timestamp']); expect(pageLoadTracker.loaded).toEqual(['Jwt']);
expect(pageLoadTracker.loaded).not.toContain('QrCode'); expect(pageLoadTracker.loaded).not.toContain('QrCode');
expect(pageLoadTracker.loaded).not.toContain('TestDataGenerator'); expect(pageLoadTracker.loaded).not.toContain('TestDataGenerator');
}); });
+6 -23
View File
@@ -9,8 +9,8 @@ import {
describe('features', () => { describe('features', () => {
describe('FEATURES', () => { describe('FEATURES', () => {
it('应该有10个功能定义', () => { it('应该有9个功能定义', () => {
expect(FEATURES).toHaveLength(10); expect(FEATURES).toHaveLength(9);
}); });
it('应该有每个功能的所有必需属性', () => { it('应该有每个功能的所有必需属性', () => {
@@ -24,12 +24,9 @@ describe('features', () => {
expect(typeof feature.label).toBe('string'); expect(typeof feature.label).toBe('string');
expect(typeof feature.description).toBe('string'); expect(typeof feature.description).toBe('string');
expect(typeof feature.defaultVisible).toBe('boolean'); expect(typeof feature.defaultVisible).toBe('boolean');
if (feature.key !== 'dashboard') {
expect(feature).toHaveProperty('icon'); expect(feature).toHaveProperty('icon');
expect(feature).toHaveProperty('themeColorKey'); expect(feature).toHaveProperty('themeColorKey');
expect(typeof feature.themeColorKey).toBe('string'); expect(typeof feature.themeColorKey).toBe('string');
}
}); });
}); });
@@ -41,13 +38,6 @@ describe('features', () => {
}); });
describe('getFeatureByKey', () => { describe('getFeatureByKey', () => {
it('应该返回dashboard功能', () => {
const feature = getFeatureByKey('dashboard');
expect(feature).toBeDefined();
expect(feature?.key).toBe('dashboard');
expect(feature?.label).toBe('仪表盘');
});
it('应该返回时间戳功能', () => { it('应该返回时间戳功能', () => {
const feature = getFeatureByKey('timestamp'); const feature = getFeatureByKey('timestamp');
expect(feature).toBeDefined(); expect(feature).toBeDefined();
@@ -78,9 +68,8 @@ describe('features', () => {
}); });
}); });
it('应该包含仪表盘、时间戳、存储清理、二维码', () => { it('应该包含时间戳、存储清理、二维码', () => {
const visibleKeys = getDefaultVisibleFeatureKeys(); const visibleKeys = getDefaultVisibleFeatureKeys();
expect(visibleKeys).toContain('dashboard');
expect(visibleKeys).toContain('timestamp'); expect(visibleKeys).toContain('timestamp');
expect(visibleKeys).toContain('storageCleaner'); expect(visibleKeys).toContain('storageCleaner');
expect(visibleKeys).toContain('qrCode'); expect(visibleKeys).toContain('qrCode');
@@ -90,8 +79,7 @@ describe('features', () => {
describe('getAllFeatureKeys', () => { describe('getAllFeatureKeys', () => {
it('应该返回所有功能key', () => { it('应该返回所有功能key', () => {
const allKeys = getAllFeatureKeys(); const allKeys = getAllFeatureKeys();
expect(allKeys).toHaveLength(10); expect(allKeys).toHaveLength(9);
expect(allKeys).toContain('dashboard');
expect(allKeys).toContain('timestamp'); expect(allKeys).toContain('timestamp');
expect(allKeys).toContain('storageCleaner'); expect(allKeys).toContain('storageCleaner');
expect(allKeys).toContain('qrCode'); expect(allKeys).toContain('qrCode');
@@ -105,9 +93,9 @@ describe('features', () => {
}); });
describe('getDefaultPageOrder', () => { describe('getDefaultPageOrder', () => {
it('应该排除仪表盘从页面顺序', () => { it('应该包含所有工具页面', () => {
const pageOrder = getDefaultPageOrder(); const pageOrder = getDefaultPageOrder();
expect(pageOrder).not.toContain('dashboard'); expect(pageOrder).toHaveLength(9);
}); });
it('应该包含时间戳、存储清理、二维码在页面顺序', () => { it('应该包含时间戳、存储清理、二维码在页面顺序', () => {
@@ -116,10 +104,5 @@ describe('features', () => {
expect(pageOrder).toContain('storageCleaner'); expect(pageOrder).toContain('storageCleaner');
expect(pageOrder).toContain('qrCode'); expect(pageOrder).toContain('qrCode');
}); });
it('应该有9个项目在页面顺序', () => {
const pageOrder = getDefaultPageOrder();
expect(pageOrder).toHaveLength(9);
});
}); });
}); });
+1 -18
View File
@@ -25,12 +25,6 @@ export interface FeatureConfig {
} }
export const FEATURES: FeatureConfig[] = [ export const FEATURES: FeatureConfig[] = [
{
key: 'dashboard',
label: '仪表盘',
description: '',
defaultVisible: true,
},
{ {
key: 'timestamp', key: 'timestamp',
label: '时间戳', label: '时间戳',
@@ -118,16 +112,5 @@ export function getAllFeatureKeys(): PageType[] {
} }
export function getDefaultPageOrder(): PageType[] { export function getDefaultPageOrder(): PageType[] {
return FEATURES.filter((f) => f.key !== 'dashboard').map((f) => f.key); return FEATURES.map((f) => f.key);
}
export function getEntryPointType(): 'popup' | 'sidepanel' | 'tab' {
const pathname = window.location.pathname;
if (pathname.includes('sidepanel')) {
return 'sidepanel';
}
if (new URLSearchParams(window.location.search).get('mode') === 'tab') {
return 'tab';
}
return 'popup';
} }
-1
View File
@@ -4,6 +4,5 @@ export {
getAllFeatureKeys, getAllFeatureKeys,
getDefaultPageOrder, getDefaultPageOrder,
getDefaultVisibleFeatureKeys, getDefaultVisibleFeatureKeys,
getEntryPointType,
getFeatureByKey, getFeatureByKey,
} from '@/config/featureMeta'; } from '@/config/featureMeta';
-5
View File
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadDashboard(): Promise<{ default: ComponentType }> {
return import('@/pages/Dashboard');
}
-2
View File
@@ -16,8 +16,6 @@ function ensurePagesStyles(): Promise<unknown> {
export function loadPage(key: PageType): Promise<PageModule> { export function loadPage(key: PageType): Promise<PageModule> {
return ensurePagesStyles().then(() => { return ensurePagesStyles().then(() => {
switch (key) { switch (key) {
case 'dashboard':
return import('@/config/pageLoaders/dashboard').then((m) => m.default());
case 'timestamp': case 'timestamp':
return import('@/config/pageLoaders/timestamp').then((m) => m.default()); return import('@/config/pageLoaders/timestamp').then((m) => m.default());
case 'storageCleaner': case 'storageCleaner':
+1 -24
View File
@@ -1,6 +1,6 @@
import '../../.wxt/types/imports.d.ts'; import '../../.wxt/types/imports.d.ts';
import { browser } from 'wxt/browser'; import { browser } from 'wxt/browser';
import { MessageAction, onMessage, sendMessage } from '@/utils/messages'; import { MessageAction, onMessage } from '@/utils/messages';
import { createAllContextMenus, parseContextMenuClick } from '@/utils/contextMenu'; import { createAllContextMenus, parseContextMenuClick } from '@/utils/contextMenu';
import { saveContextMenuData } from '@/utils/useContextMenuData'; import { saveContextMenuData } from '@/utils/useContextMenuData';
import { mainWorldInjectionScript } from '@/utils/rightClickInjection'; import { mainWorldInjectionScript } from '@/utils/rightClickInjection';
@@ -24,18 +24,6 @@ export default defineBackground(() => {
const { featureKey, payload } = result.data; const { featureKey, payload } = result.data;
try {
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 (err) {
console.debug('[Context Menu] Side panel pipeline is not available:', err);
}
await saveContextMenuData({ featureKey, payload }); await saveContextMenuData({ featureKey, payload });
try { try {
@@ -45,17 +33,6 @@ export default defineBackground(() => {
} }
}); });
// 扩展图标点击时打开侧边栏
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 via extension action clicked:', err);
}
}
});
// 3. 注入主环境脚本(content script 无权访问 chrome.tabs/scripting,委托 background 执行) // 3. 注入主环境脚本(content script 无权访问 chrome.tabs/scripting,委托 background 执行)
onMessage(MessageAction.INJECT_MAIN_WORLD_SCRIPT, async (message) => { onMessage(MessageAction.INJECT_MAIN_WORLD_SCRIPT, async (message) => {
const sender = message.sender as chrome.runtime.MessageSender | undefined; const sender = message.sender as chrome.runtime.MessageSender | undefined;
+10 -22
View File
@@ -1,36 +1,24 @@
import RouterProvider from '@/providers/RouterProvider'; import RouterProvider from '@/providers/RouterProvider';
import TopBar from '@/layout/TopBar'; import FeatureNav from '@/layout/FeatureNav';
import RouterContainer from '@/components/RouterContainer'; import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary'; import ErrorBoundary from '@/components/ErrorBoundary';
import { getEntryPointType } from '@/config/features';
export default function App() { export default function App() {
const entryType = getEntryPointType();
const routerConfig =
entryType === 'tab'
? {
syncKey: 'app/tabRoute' as const,
visiblePagesKey: 'app/tabVisiblePages' as const,
pageOrderKey: 'app/tabPageOrder' as const,
}
: {
syncKey: 'app/popupRoute' as const,
visiblePagesKey: 'app/popupVisiblePages' as const,
pageOrderKey: 'app/popupPageOrder' as const,
};
return ( return (
<RouterProvider <RouterProvider
syncKey={routerConfig.syncKey} defaultRoute="timestamp"
visiblePagesKey={routerConfig.visiblePagesKey} syncKey="app/popupRoute"
pageOrderKey={routerConfig.pageOrderKey} visiblePagesKey="app/popupVisiblePages"
pageOrderKey="app/popupPageOrder"
> >
<div className="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"> <div className="flex w-[450px] max-w-[450px] min-w-[450px] h-[600px] min-h-[600px] overflow-hidden bg-background">
<TopBar /> <div className="flex flex-1 min-w-0 flex-col">
<ErrorBoundary> <ErrorBoundary>
<RouterContainer /> <RouterContainer />
</ErrorBoundary> </ErrorBoundary>
</div> </div>
<FeatureNav />
</div>
</RouterProvider> </RouterProvider>
); );
} }
+2 -9
View File
@@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Testing Tools - 标签页</title> <title>Testing Tools</title>
<meta name="manifest.type" content="browser_action" /> <meta name="manifest.type" content="browser_action" />
<script> <script>
(function () { (function () {
@@ -21,7 +21,7 @@
<style> <style>
/* Force initial popup size before React hydration */ /* Force initial popup size before React hydration */
html, body { html, body {
width: 400px; width: 450px;
height: 600px; height: 600px;
margin: 0; margin: 0;
padding: 0; padding: 0;
@@ -33,13 +33,6 @@
width: 100%; width: 100%;
height: 100%; height: 100%;
} }
/* If opened in a tab (mode=tab), reset the fixed size */
@media screen and (min-width: 600px) {
html, body {
width: 100%;
height: 100%;
}
}
</style> </style>
</head> </head>
<body> <body>
-26
View File
@@ -1,26 +0,0 @@
import { useEffect } from 'react';
import RouterProvider from '@/providers/RouterProvider';
import TopBar from '@/layout/TopBar';
import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary';
import { MessageAction, sendMessage } from '@/utils/messages';
export default function App() {
useEffect(() => {
sendMessage(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: true });
return () => {
sendMessage(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: false });
};
}, []);
return (
<RouterProvider defaultRoute="dashboard" syncKey="app/sidepanelRoute">
<div className="flex flex-col h-screen w-full overflow-hidden">
<TopBar />
<ErrorBoundary>
<RouterContainer />
</ErrorBoundary>
</div>
</RouterProvider>
);
}
-25
View File
@@ -1,25 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Testing Tools - Side Panel</title>
<script>
(function () {
try {
var raw = localStorage.getItem('snapshot/app/themeMode');
var mode = raw ? JSON.parse(raw) : 'system';
if (mode !== 'light' && mode !== 'dark' && mode !== 'system') mode = 'system';
var isDark =
mode === 'dark' ||
(mode === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
if (isDark) document.documentElement.classList.add('dark');
} catch (_error) {}
})();
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
-10
View File
@@ -1,10 +0,0 @@
import ReactDOM from 'react-dom/client';
import AppRoot from '@/providers/AppRoot';
import '@/styles/shell.css';
import App from './App.tsx';
ReactDOM.createRoot(document.getElementById('root')!).render(
<AppRoot>
<App />
</AppRoot>,
);
@@ -0,0 +1,20 @@
import { Button } from '@/components/ui/button';
import { useThemeToggle } from './useThemeToggle';
export default function ThemeToggleButton() {
const { ThemeIcon, themeTitle, cycleThemeMode } = useThemeToggle();
return (
<Button
type="button"
variant="ghost"
size="icon"
onClick={cycleThemeMode}
title={themeTitle}
aria-label={themeTitle}
className="h-9 w-9 text-muted-foreground hover:text-foreground"
>
<ThemeIcon className="h-4 w-4" aria-hidden="true" />
</Button>
);
}
@@ -0,0 +1,82 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import type { PageType } from '@/types/storage';
import FeatureNav from '@/layout/FeatureNav';
import { ThemeModeProvider } from '@/providers/ThemeModeProvider';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
const mockNavigateTo = vi.fn();
const mockRouterValue = {
currentPage: 'timestamp' as PageType,
visiblePages: ['timestamp', 'jwt', 'storageCleaner'] as PageType[],
pageOrder: ['jwt', 'timestamp', 'storageCleaner'] as PageType[],
recentlyUsedTools: [] as PageType[],
isLoaded: true,
navigateTo: mockNavigateTo,
setVisiblePages: vi.fn(),
setPageOrder: vi.fn(),
};
vi.mock('@/providers/RouterProvider', () => ({
useRouter: () => mockRouterValue,
}));
describe('FeatureNav 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
mockRouterValue.currentPage = 'timestamp';
mockRouterValue.pageOrder = ['jwt', 'timestamp', 'storageCleaner'];
mockRouterValue.visiblePages = ['timestamp', 'jwt', 'storageCleaner'];
});
const renderFeatureNav = () =>
render(
<ThemeModeProvider>
<FeatureNav />
</ThemeModeProvider>,
);
it('应渲染全部可见工具图标', () => {
renderFeatureNav();
expect(screen.getByLabelText('JWT 解析')).toBeInTheDocument();
expect(screen.getByLabelText('时间戳')).toBeInTheDocument();
expect(screen.getByLabelText('存储清理')).toBeInTheDocument();
});
it('点击图标应调用 navigateTo', () => {
renderFeatureNav();
fireEvent.click(screen.getByLabelText('JWT 解析'));
expect(mockNavigateTo).toHaveBeenCalledWith('jwt');
});
it('当前页对应项应有 active 样式与 aria-current', () => {
renderFeatureNav();
const activeButton = screen.getByLabelText('时间戳');
expect(activeButton).toHaveAttribute('aria-current', 'page');
expect(activeButton).toHaveClass('bg-muted');
expect(activeButton).toHaveClass('border-primary');
});
it('应渲染主题切换按钮', () => {
renderFeatureNav();
expect(screen.getByLabelText(/切换到/)).toBeInTheDocument();
});
});
@@ -1,14 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
import * as featureConfig from '@/config/features'; import * as featureConfig from '@/config/features';
import { resolveDashboardFeatures } from '../dashboardFeatures'; import { resolveNavFeatures } from '../resolveNavFeatures';
describe('resolveDashboardFeatures', () => { describe('resolveNavFeatures', () => {
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks(); vi.restoreAllMocks();
}); });
it('应按 keys 顺序返回可见工具,并排除 dashboard', () => { it('应按 keys 顺序返回可见工具', () => {
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard', 'timestamp', 'jwt']); const items = resolveNavFeatures(['jwt', 'timestamp'], ['timestamp', 'jwt']);
expect(items.map((item) => item.key)).toEqual(['jwt', 'timestamp']); expect(items.map((item) => item.key)).toEqual(['jwt', 'timestamp']);
expect(items.map((item) => item.feature.label)).toEqual(['JWT 解析', '时间戳']); expect(items.map((item) => item.feature.label)).toEqual(['JWT 解析', '时间戳']);
@@ -24,25 +24,34 @@ describe('resolveDashboardFeatures', () => {
return feature; return feature;
}); });
const items = resolveDashboardFeatures(['timestamp'], ['dashboard', 'timestamp']); const items = resolveNavFeatures(['timestamp'], ['timestamp']);
expect(items.map((item) => item.key)).toEqual(['timestamp']); expect(items.map((item) => item.key)).toEqual(['timestamp']);
}); });
it('应过滤不在 visiblePages 中的工具', () => { it('应过滤不在 visiblePages 中的工具', () => {
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard', 'timestamp']); const items = resolveNavFeatures(['jwt', 'timestamp'], ['timestamp']);
expect(items.map((item) => item.key)).toEqual(['timestamp']); expect(items.map((item) => item.key)).toEqual(['timestamp']);
}); });
it('visiblePages 无匹配工具时应返回空列表', () => { it('visiblePages 无匹配工具时应返回空列表', () => {
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard']); const items = resolveNavFeatures(['jwt', 'timestamp'], []);
expect(items).toEqual([]); expect(items).toEqual([]);
}); });
it('应过滤缺少 icon 的工具', () => { it('应过滤缺少 icon 的工具', () => {
const items = resolveDashboardFeatures(['dashboard', 'timestamp'], ['dashboard', 'timestamp']); const originalGetFeatureByKey = featureConfig.getFeatureByKey;
vi.spyOn(featureConfig, 'getFeatureByKey').mockImplementation((key) => {
const feature = originalGetFeatureByKey(key);
if (key === 'jwt' && feature) {
return { ...feature, icon: undefined };
}
return feature;
});
const items = resolveNavFeatures(['jwt', 'timestamp'], ['jwt', 'timestamp']);
expect(items.map((item) => item.key)).toEqual(['timestamp']); expect(items.map((item) => item.key)).toEqual(['timestamp']);
}); });
+39
View File
@@ -0,0 +1,39 @@
import { cn } from '@/lib/utils';
import ThemeToggleButton from './ThemeToggleButton';
import { useFeatureNav } from './useFeatureNav';
export default function FeatureNav() {
const { navItems, currentPage, navigateTo } = useFeatureNav();
return (
<nav aria-label="功能导航" className="flex w-12 shrink-0 flex-col border-l border-border py-2">
<div className="flex flex-1 flex-col items-center gap-1 overflow-y-auto">
{navItems.map(({ key, feature }) => {
const Icon = feature.icon;
const isActive = currentPage === key;
return (
<button
key={key}
type="button"
title={feature.label}
aria-label={feature.label}
aria-current={isActive ? 'page' : undefined}
onClick={() => navigateTo(key)}
className={cn(
'flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground',
isActive && 'border-l-2 border-primary bg-muted text-foreground',
)}
>
<Icon className="h-4 w-4" aria-hidden="true" />
</button>
);
})}
</div>
<div className="mt-1 flex shrink-0 items-center justify-center border-t border-border pt-1">
<ThemeToggleButton />
</div>
</nav>
);
}
@@ -0,0 +1,27 @@
import { getFeatureByKey, type FeatureConfig } from '@/config/features';
import type { PageType } from '@/types/storage';
export interface NavFeatureItem {
key: PageType;
feature: FeatureConfig & { icon: NonNullable<FeatureConfig['icon']> };
}
function isNavFeature(feature: FeatureConfig): feature is NavFeatureItem['feature'] {
return feature.icon != null;
}
export function resolveNavFeatures(keys: PageType[], visiblePages: PageType[]): NavFeatureItem[] {
const visibleSet = new Set(visiblePages);
const items: NavFeatureItem[] = [];
for (const key of keys) {
if (!visibleSet.has(key)) continue;
const feature = getFeatureByKey(key);
if (!feature || !isNavFeature(feature)) continue;
items.push({ key, feature });
}
return items;
}
+21
View File
@@ -0,0 +1,21 @@
import { useMemo } from 'react';
import { useRouter } from '@/providers/RouterProvider';
import type { PageType } from '@/types/storage';
import { resolveNavFeatures, type NavFeatureItem } from './resolveNavFeatures';
export interface UseFeatureNavReturn {
navItems: NavFeatureItem[];
currentPage: PageType;
navigateTo: (page: PageType) => void;
}
export function useFeatureNav(): UseFeatureNavReturn {
const { currentPage, pageOrder, visiblePages, navigateTo } = useRouter();
const navItems = useMemo(
() => resolveNavFeatures(pageOrder, visiblePages),
[pageOrder, visiblePages],
);
return { navItems, currentPage, navigateTo };
}
+24
View File
@@ -0,0 +1,24 @@
import { Monitor, Moon, Sun } from 'lucide-react';
import { useThemeMode } from '@/providers/ThemeModeProvider';
export interface UseThemeToggleReturn {
ThemeIcon: typeof Sun;
themeTitle: string;
cycleThemeMode: () => void;
}
export function useThemeToggle(): UseThemeToggleReturn {
const { mode, setMode } = useThemeMode();
const cycleThemeMode = () => {
const nextMap = { light: 'dark', dark: 'system', system: 'light' } as const;
setMode(nextMap[mode]);
};
const ThemeIcon = mode === 'light' ? Sun : mode === 'dark' ? Moon : Monitor;
const themeTitle =
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
return { ThemeIcon, themeTitle, cycleThemeMode };
}
+8 -10
View File
@@ -5,22 +5,20 @@
## 组件列表 ## 组件列表
| 目录 | 用途 | | 目录 | 用途 |
| --------- | -------------------------------------------------------------- | | ------------- | ------------------------------------------ |
| `TopBar/` | 顶部导航栏:搜索(含历史记录)、主题切换、返回导航、标签页打开 | | `FeatureNav/` | 右侧功能导航栏:工具图标切换、底部主题切换 |
## 目录结构 ## 目录结构
遵循与 `pages/` 相同的 UI + Hook 分离模式: 遵循与 `pages/` 相同的 UI + Hook 分离模式:
``` ```
layout/TopBar/ layout/FeatureNav/
├── index.tsx # 布局入口 ├── index.tsx # 垂直图标导航 + 底部主题按钮
├── useTopBar.ts # 业务逻辑 Hook ├── useFeatureNav.ts # 读路由状态,暴露 navItems / navigateTo
├── constants.ts # 常量 ├── useThemeToggle.ts # 主题模式循环切换逻辑
├── SearchInput.tsx # 搜索输入框 ├── ThemeToggleButton.tsx # 主题切换按钮
├── SearchDropdown.tsx # 搜索结果/历史下拉面板 ├── resolveNavFeatures.ts # 功能列表解析
├── SearchResultItem.tsx # 单条搜索结果项
├── TopBarActions.tsx # 右侧操作按钮组
└── __tests__/ └── __tests__/
└── index.test.tsx └── index.test.tsx
``` ```
-45
View File
@@ -1,45 +0,0 @@
import { type FeatureConfig } from '@/config/features';
import SearchResultItem from './SearchResultItem';
interface SearchDropdownProps {
searchQuery: string;
searchResults: FeatureConfig[];
recentFeatures: FeatureConfig[];
selectedIndex: number;
onSelect: (feature: FeatureConfig) => void;
}
export default function SearchDropdown({
searchQuery,
searchResults,
recentFeatures,
selectedIndex,
onSelect,
}: SearchDropdownProps) {
const isSearching = !!searchQuery.trim();
const items = isSearching ? searchResults : recentFeatures;
return (
<div className="absolute left-0 right-0 top-full z-50 mt-1.5 max-h-80 overflow-y-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-lg fade-in-slide-top-2">
<ul role="listbox" className="p-1.5">
{!isSearching && items.length > 0 && (
<li className="px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/60">
</li>
)}
{isSearching && items.length === 0 ? (
<li className="px-4 py-6 text-center text-sm text-muted-foreground"></li>
) : (
items.map((feature, index) => (
<SearchResultItem
key={feature.key}
feature={feature}
selected={selectedIndex === index}
onSelect={onSelect}
/>
))
)}
</ul>
</div>
);
}
-55
View File
@@ -1,55 +0,0 @@
import { type KeyboardEvent, type RefObject } from 'react';
import { Search, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { getSearchShortcutLabel } from './constants';
interface SearchInputProps {
inputRef: RefObject<HTMLInputElement | null>;
searchQuery: string;
onSearchQueryChange: (value: string) => void;
onFocus: () => void;
onKeyDown: (e: KeyboardEvent) => void;
onClear: () => void;
}
export default function SearchInput({
inputRef,
searchQuery,
onSearchQueryChange,
onFocus,
onKeyDown,
onClear,
}: SearchInputProps) {
return (
<div className="group relative">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/60 transition-colors group-focus-within:text-muted-foreground" />
<Input
ref={inputRef}
placeholder="搜索工具..."
value={searchQuery}
onChange={(e) => onSearchQueryChange(e.target.value)}
onFocus={onFocus}
onKeyDown={onKeyDown}
aria-label="搜索工具..."
className="h-9 rounded-lg border-border/60 bg-muted/40 pl-9 pr-16 shadow-none focus-visible:ring-1 focus-visible:ring-offset-0 placeholder:text-muted-foreground/50"
/>
{searchQuery ? (
<Button
type="button"
variant="ghost"
size="icon"
onClick={onClear}
aria-label="清除搜索"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3 w-3" />
</Button>
) : (
<kbd className="pointer-events-none absolute right-3 top-1/2 hidden h-5 -translate-y-1/2 items-center rounded border border-border/60 bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground/60 sm:inline-flex">
{getSearchShortcutLabel()}
</kbd>
)}
</div>
);
}
-30
View File
@@ -1,30 +0,0 @@
import { type FeatureConfig } from '@/config/features';
import { cn } from '@/lib/utils';
interface SearchResultItemProps {
feature: FeatureConfig;
selected: boolean;
onSelect: (feature: FeatureConfig) => void;
}
export default function SearchResultItem({ feature, selected, onSelect }: SearchResultItemProps) {
return (
<li
role="option"
aria-selected={selected}
onClick={() => onSelect(feature)}
className={cn(
'flex cursor-pointer items-center gap-3 rounded-md px-3 py-2.5 text-sm transition-colors',
selected ? 'bg-accent text-accent-foreground' : 'hover:bg-muted/60',
)}
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-muted/80 text-muted-foreground">
{feature.icon && <feature.icon className="h-4 w-4" />}
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-foreground">{feature.label}</p>
<p className="mt-0.5 truncate text-xs text-muted-foreground">{feature.description}</p>
</div>
</li>
);
}
-34
View File
@@ -1,34 +0,0 @@
import { type LucideIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
interface TopBarAction {
id: string;
icon: LucideIcon;
title: string;
onClick: () => void;
}
interface TopBarActionsProps {
actions: TopBarAction[];
}
export default function TopBarActions({ actions }: TopBarActionsProps) {
return (
<div className="flex shrink-0 items-center gap-1">
{actions.map(({ id, icon: Icon, title, onClick }) => (
<Button
key={id}
type="button"
variant="ghost"
size="icon"
onClick={onClick}
title={title}
aria-label={title}
className="h-8 w-8 text-muted-foreground"
>
<Icon className="h-4 w-4" />
</Button>
))}
</div>
);
}
@@ -1,37 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getSearchShortcutLabel } from '@/layout/TopBar/constants';
describe('getSearchShortcutLabel', () => {
const originalUserAgent = navigator.userAgent;
afterEach(() => {
vi.stubGlobal('navigator', { ...navigator, userAgent: originalUserAgent });
});
it('macOS 应显示 ⌘K', () => {
vi.stubGlobal('navigator', {
...navigator,
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
});
expect(getSearchShortcutLabel()).toBe('⌘K');
});
it('Windows 应显示 Ctrl+K', () => {
vi.stubGlobal('navigator', {
...navigator,
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
});
expect(getSearchShortcutLabel()).toBe('Ctrl+K');
});
it('Linux 应显示 Ctrl+K', () => {
vi.stubGlobal('navigator', {
...navigator,
userAgent:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
});
expect(getSearchShortcutLabel()).toBe('Ctrl+K');
});
});
@@ -1,76 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import type { PageType } from '@/types/storage';
import React from 'react';
import TopBar from '@/layout/TopBar';
import { RouterProvider } from '@/providers/RouterProvider';
import { ThemeModeProvider } from '@/providers/ThemeModeProvider';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
const mockRouterValue = {
currentPage: 'dashboard' as PageType,
visiblePages: ['dashboard', 'timestamp'] as PageType[],
pageOrder: ['timestamp'] as PageType[],
isLoaded: true,
navigateTo: vi.fn(),
syncNavigation: vi.fn(),
goHome: vi.fn(),
setVisiblePages: vi.fn(),
setPageOrder: vi.fn(),
};
vi.mock('@/providers/RouterProvider', () => ({
useRouter: () => mockRouterValue,
RouterProvider: ({ children }: { children: React.ReactNode }) => children,
}));
describe('TopBar 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
});
const renderWithProvider = (ui: React.ReactElement) => {
return render(
<ThemeModeProvider>
<RouterProvider>{ui}</RouterProvider>
</ThemeModeProvider>,
);
};
describe('渲染测试', () => {
it('不在 dashboard 时应渲染返回按钮', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<TopBar />);
expect(screen.getByLabelText('返回首页')).toBeInTheDocument();
});
it('在 dashboard 上不应渲染返回按钮', () => {
mockRouterValue.currentPage = 'dashboard';
renderWithProvider(<TopBar />);
expect(screen.queryByLabelText('返回首页')).not.toBeInTheDocument();
});
});
describe('交互测试', () => {
it('点击返回按钮时应调用 goHome', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<TopBar />);
fireEvent.click(screen.getByLabelText('返回首页'));
expect(mockRouterValue.goHome).toHaveBeenCalledTimes(1);
});
});
});
-9
View File
@@ -1,9 +0,0 @@
export const SEARCH_HISTORY_LIMIT = 10;
export const SEARCH_HISTORY_DISPLAY = 5;
export const isSearchHistory = (val: unknown): val is string[] =>
Array.isArray(val) && val.every((item) => typeof item === 'string');
export function getSearchShortcutLabel(): string {
return /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent) ? '⌘K' : 'Ctrl+K';
}
-80
View File
@@ -1,80 +0,0 @@
import { ArrowLeft, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import SearchDropdown from './SearchDropdown';
import SearchInput from './SearchInput';
import TopBarActions from './TopBarActions';
import { useTopBar } from './useTopBar';
export default function TopBar() {
const {
searchQuery,
searchResults,
recentFeatures,
selectedIndex,
isDashboard,
ThemeIcon,
themeTitle,
showDropdown,
containerRef,
inputRef,
handleSearchQueryChange,
handleSearchFocus,
handleSelectFeature,
handleKeyDown,
cycleThemeMode,
handleOpenInTab,
goHome,
clearSearch,
} = useTopBar();
const actions = [
{ id: 'theme', icon: ThemeIcon, title: themeTitle, onClick: cycleThemeMode },
{
id: 'open-in-tab',
icon: ExternalLink,
title: '在标签页打开',
onClick: () => void handleOpenInTab(),
},
];
return (
<header className="relative z-50 flex h-14 items-center justify-between border-b border-border bg-background px-4">
<div className="flex w-10 items-center justify-start">
{!isDashboard && (
<Button
type="button"
variant="outline"
size="icon"
onClick={goHome}
aria-label="返回首页"
className="h-8 w-8 shadow-sm text-muted-foreground"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
</div>
<div ref={containerRef} className="relative mx-4 max-w-md flex-1">
<SearchInput
inputRef={inputRef}
searchQuery={searchQuery}
onSearchQueryChange={handleSearchQueryChange}
onFocus={handleSearchFocus}
onKeyDown={handleKeyDown}
onClear={clearSearch}
/>
{showDropdown && (
<SearchDropdown
searchQuery={searchQuery}
searchResults={searchResults}
recentFeatures={recentFeatures}
selectedIndex={selectedIndex}
onSelect={handleSelectFeature}
/>
)}
</div>
<TopBarActions actions={actions} />
</header>
);
}
-182
View File
@@ -1,182 +0,0 @@
import {
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type RefObject,
} from 'react';
import { Monitor, Moon, Sun } from 'lucide-react';
import { useRouter } from '@/providers/RouterProvider';
import { useThemeMode } from '@/providers/ThemeModeProvider';
import { type FeatureConfig, FEATURES } from '@/config/features';
import { useStorageState } from '@/utils/useStorageState';
import { openExtensionPage } from '@/utils/chromeTabs';
import { isSearchHistory, SEARCH_HISTORY_DISPLAY, SEARCH_HISTORY_LIMIT } from './constants';
export interface UseTopBarReturn {
searchQuery: string;
searchResults: FeatureConfig[];
recentFeatures: FeatureConfig[];
selectedIndex: number;
isDashboard: boolean;
ThemeIcon: typeof Sun;
themeTitle: string;
showDropdown: boolean;
containerRef: RefObject<HTMLDivElement | null>;
inputRef: RefObject<HTMLInputElement | null>;
handleSearchQueryChange: (value: string) => void;
handleSearchFocus: () => void;
handleSelectFeature: (feature: FeatureConfig) => void;
handleKeyDown: (e: ReactKeyboardEvent) => void;
cycleThemeMode: () => void;
handleOpenInTab: () => Promise<void>;
goHome: () => void;
clearSearch: () => void;
}
export function useTopBar(): UseTopBarReturn {
const { currentPage, goHome, navigateTo } = useRouter();
const { mode, setMode } = useThemeMode();
const [searchQuery, setSearchQuery] = useState('');
const [showResults, setShowResults] = useState(false);
const [searchHistory, setSearchHistory] = useStorageState(
'app/searchHistory',
[],
isSearchHistory,
);
const [selectedIndex, setSelectedIndex] = useState(-1);
const containerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const handleOpenInTab = async () => {
await openExtensionPage('popup.html', { mode: 'tab' });
window.close();
};
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setShowResults(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
useEffect(() => {
const handleGlobalKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
inputRef.current?.focus();
setShowResults(true);
}
};
document.addEventListener('keydown', handleGlobalKeyDown);
return () => document.removeEventListener('keydown', handleGlobalKeyDown);
}, []);
const searchResults = useMemo(() => {
const query = searchQuery.trim().toLowerCase();
if (!query) return [];
return FEATURES.filter((f) => {
if (f.key === 'dashboard') return false;
return f.label.toLowerCase().includes(query) || f.description.toLowerCase().includes(query);
});
}, [searchQuery]);
const recentFeatures = useMemo(() => {
if (searchQuery.trim()) return [];
return searchHistory
.slice(0, SEARCH_HISTORY_DISPLAY)
.map((key) => FEATURES.find((f) => f.key === key))
.filter((feature): feature is FeatureConfig => !!feature && feature.key !== 'dashboard');
}, [searchHistory, searchQuery]);
const saveToHistory = (featureKey: string) => {
setSearchHistory((prev) =>
[featureKey, ...prev.filter((h) => h !== featureKey)].slice(0, SEARCH_HISTORY_LIMIT),
);
};
const handleSelectFeature = (feature: FeatureConfig) => {
navigateTo(feature.key);
saveToHistory(feature.key);
setSearchQuery('');
setShowResults(false);
};
const cycleThemeMode = () => {
const nextMap = { light: 'dark', dark: 'system', system: 'light' } as const;
setMode(nextMap[mode]);
};
const ThemeIcon = mode === 'light' ? Sun : mode === 'dark' ? Moon : Monitor;
const themeTitle =
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
const handleKeyDown = (e: ReactKeyboardEvent) => {
const isSearching = !!searchQuery.trim();
const items = isSearching ? searchResults : recentFeatures;
const totalItems = items.length;
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedIndex((prev) => (prev < totalItems - 1 ? prev + 1 : prev));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
} else if (e.key === 'Enter') {
e.preventDefault();
let feature: FeatureConfig | undefined;
if (selectedIndex >= 0 && selectedIndex < totalItems) {
feature = items[selectedIndex];
} else if (isSearching && searchResults.length > 0) {
feature = searchResults[0];
}
if (feature) handleSelectFeature(feature);
} else if (e.key === 'Escape') {
setShowResults(false);
inputRef.current?.blur();
}
};
const clearSearch = () => {
setSearchQuery('');
setSelectedIndex(-1);
};
const handleSearchQueryChange = (value: string) => {
setSearchQuery(value);
setShowResults(true);
setSelectedIndex(-1);
};
const handleSearchFocus = () => setShowResults(true);
const showDropdown = showResults && (!!searchQuery.trim() || recentFeatures.length > 0);
return {
searchQuery,
searchResults,
recentFeatures,
selectedIndex,
showDropdown,
isDashboard: currentPage === 'dashboard',
ThemeIcon,
themeTitle,
containerRef,
inputRef,
handleSearchQueryChange,
handleSearchFocus,
handleSelectFeature,
handleKeyDown,
cycleThemeMode,
handleOpenInTab,
goHome,
clearSearch,
};
}
@@ -2,15 +2,6 @@ import { describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import Base64ConverterPage from '../index'; import Base64ConverterPage from '../index';
// Mock getEntryPointType
vi.mock('@/config/features', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/config/features')>();
return {
...actual,
getEntryPointType: () => 'sidepanel',
};
});
// Mock 子组件 // Mock 子组件
vi.mock('../components/TextMode', () => ({ vi.mock('../components/TextMode', () => ({
default: ({ onSwitchToImageMode }: { onSwitchToImageMode?: () => void }) => ( default: ({ onSwitchToImageMode }: { onSwitchToImageMode?: () => void }) => (
@@ -1,95 +0,0 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { resolveDashboardFeatures, type DashboardFeatureItem } from '../dashboardFeatures';
import Index from '../index';
const mockNavigateTo = vi.fn();
const mockUseDashboard = vi.fn();
vi.mock('../useDashboard', () => ({
useDashboard: () => mockUseDashboard(),
}));
function buildFeatureItem(key: 'timestamp' | 'jwt'): DashboardFeatureItem {
return resolveDashboardFeatures([key], [key])[0]!;
}
describe('Dashboard 页面', () => {
beforeEach(() => {
vi.clearAllMocks();
mockUseDashboard.mockReturnValue({
visibleFeatures: [buildFeatureItem('timestamp'), buildFeatureItem('jwt')],
recentFeatures: [],
showRecent: false,
navigateTo: mockNavigateTo,
});
});
it('应渲染全部工具网格', () => {
render(<Index />);
expect(screen.getByText('全部工具')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '时间戳' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'JWT 解析' })).toBeInTheDocument();
});
it('点击工具卡片应触发 navigateTo', async () => {
const user = userEvent.setup();
render(<Index />);
await user.click(screen.getByRole('button', { name: '时间戳' }));
expect(mockNavigateTo).toHaveBeenCalledTimes(1);
expect(mockNavigateTo).toHaveBeenCalledWith('timestamp');
});
it('有最近使用数据时应显示最近使用区块', () => {
mockUseDashboard.mockReturnValue({
visibleFeatures: [buildFeatureItem('timestamp')],
recentFeatures: [buildFeatureItem('jwt')],
showRecent: true,
navigateTo: mockNavigateTo,
});
render(<Index />);
expect(screen.getByText('最近使用')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'JWT 解析' })).toBeInTheDocument();
});
it('无最近使用数据时不应显示最近使用区块', () => {
render(<Index />);
expect(screen.queryByText('最近使用')).not.toBeInTheDocument();
});
it('点击最近使用按钮应触发 navigateTo', async () => {
const user = userEvent.setup();
mockUseDashboard.mockReturnValue({
visibleFeatures: [buildFeatureItem('timestamp')],
recentFeatures: [buildFeatureItem('jwt')],
showRecent: true,
navigateTo: mockNavigateTo,
});
render(<Index />);
await user.click(screen.getByRole('button', { name: 'JWT 解析' }));
expect(mockNavigateTo).toHaveBeenCalledWith('jwt');
});
it('无可见工具时应显示空状态', () => {
mockUseDashboard.mockReturnValue({
visibleFeatures: [],
recentFeatures: [],
showRecent: false,
navigateTo: mockNavigateTo,
});
render(<Index />);
expect(screen.getByText('没有可用的工具')).toBeInTheDocument();
});
});
@@ -1,78 +0,0 @@
import { renderHook } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { useRouter } from '@/providers/RouterProvider';
import { useDashboard } from '../useDashboard';
import type { PageType } from '@/types/storage';
vi.mock('@/providers/RouterProvider', () => ({
useRouter: vi.fn(),
}));
const mockNavigateTo = vi.fn();
function mockRouterState(
overrides: {
visiblePages?: PageType[];
pageOrder?: PageType[];
recentlyUsedTools?: PageType[];
} = {},
) {
vi.mocked(useRouter).mockReturnValue({
currentPage: 'dashboard',
visiblePages: overrides.visiblePages ?? ['dashboard', 'timestamp', 'jwt'],
pageOrder: overrides.pageOrder ?? ['jwt', 'timestamp'],
recentlyUsedTools: overrides.recentlyUsedTools ?? [],
isLoaded: true,
navigateTo: mockNavigateTo,
goHome: vi.fn(),
setVisiblePages: vi.fn(),
setPageOrder: vi.fn(),
});
}
describe('useDashboard', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('应透传 router 中的 navigateTo', () => {
mockRouterState();
const { result } = renderHook(() => useDashboard());
expect(result.current.navigateTo).toBe(mockNavigateTo);
});
it('recentlyUsedTools 有可见工具时应显示最近使用', () => {
mockRouterState({
visiblePages: ['dashboard', 'timestamp', 'jwt'],
recentlyUsedTools: ['timestamp', 'jwt'],
});
const { result } = renderHook(() => useDashboard());
expect(result.current.showRecent).toBe(true);
expect(result.current.recentFeatures.map((item) => item.key)).toEqual(['timestamp', 'jwt']);
});
it('recentlyUsedTools 为空时不应显示最近使用', () => {
mockRouterState({ recentlyUsedTools: [] });
const { result } = renderHook(() => useDashboard());
expect(result.current.showRecent).toBe(false);
expect(result.current.recentFeatures).toEqual([]);
});
it('最近使用中的不可见工具应被过滤', () => {
mockRouterState({
visiblePages: ['dashboard', 'timestamp'],
recentlyUsedTools: ['jwt', 'timestamp'],
});
const { result } = renderHook(() => useDashboard());
expect(result.current.showRecent).toBe(true);
expect(result.current.recentFeatures.map((item) => item.key)).toEqual(['timestamp']);
});
});
-34
View File
@@ -1,34 +0,0 @@
import { getFeatureByKey, type FeatureConfig } from '@/config/features';
import type { PageType } from '@/types/storage';
export type DashboardFeature = FeatureConfig & {
icon: NonNullable<FeatureConfig['icon']>;
};
export interface DashboardFeatureItem {
key: PageType;
feature: DashboardFeature;
}
function isDashboardFeature(feature: FeatureConfig): feature is DashboardFeature {
return feature.icon != null;
}
export function resolveDashboardFeatures(
keys: PageType[],
visiblePages: PageType[],
): DashboardFeatureItem[] {
const visibleSet = new Set(visiblePages);
const items: DashboardFeatureItem[] = [];
for (const key of keys) {
if (!visibleSet.has(key)) continue;
const feature = getFeatureByKey(key);
if (!feature || !isDashboardFeature(feature)) continue;
items.push({ key, feature });
}
return items;
}
-61
View File
@@ -1,61 +0,0 @@
import { useDashboard } from './useDashboard';
export default function Index() {
const { visibleFeatures, recentFeatures, showRecent, navigateTo } = useDashboard();
return (
<div className="flex flex-col gap-4 p-3.5 w-full h-auto select-none">
{showRecent && (
<div className="flex flex-col gap-2">
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
使
</h3>
<div className="flex flex-wrap gap-2">
{recentFeatures.map(({ key, feature }) => {
const IconComponent = feature.icon;
return (
<button
key={key}
type="button"
onClick={() => navigateTo(key)}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border border-border/60 bg-card text-card-foreground hover:bg-muted/40 hover:border-primary/30 transition-colors cursor-pointer"
>
<IconComponent className="h-3.5 w-3.5 text-muted-foreground/70" />
{feature.label}
</button>
);
})}
</div>
</div>
)}
<div className="flex flex-col gap-2">
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
</h3>
{visibleFeatures.length === 0 ? (
<p className="text-sm text-muted-foreground py-4 text-center"></p>
) : (
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2">
{visibleFeatures.map(({ key, feature }) => {
const IconComponent = feature.icon;
return (
<button
key={key}
type="button"
onClick={() => navigateTo(key)}
className="group flex flex-col items-center justify-center gap-1.5 py-3 px-2 rounded-xl border border-border/50 bg-card hover:bg-muted/40 hover:border-primary/30 transition-colors cursor-pointer"
>
<IconComponent className="h-5 w-5 text-muted-foreground/70 group-hover:text-foreground transition-colors" />
<span className="text-[11px] font-medium text-muted-foreground/80 group-hover:text-foreground leading-tight text-center truncate w-full transition-colors">
{feature.label}
</span>
</button>
);
})}
</div>
)}
</div>
</div>
);
}
-29
View File
@@ -1,29 +0,0 @@
import { useMemo } from 'react';
import { useRouter } from '@/providers/RouterProvider';
import type { PageType } from '@/types/storage';
import { resolveDashboardFeatures, type DashboardFeatureItem } from './dashboardFeatures';
export interface UseDashboardReturn {
visibleFeatures: DashboardFeatureItem[];
recentFeatures: DashboardFeatureItem[];
showRecent: boolean;
navigateTo: (page: PageType) => void;
}
export function useDashboard(): UseDashboardReturn {
const { navigateTo, visiblePages, pageOrder, recentlyUsedTools } = useRouter();
const visibleFeatures = useMemo(
() => resolveDashboardFeatures(pageOrder, visiblePages),
[pageOrder, visiblePages],
);
const recentFeatures = useMemo(
() => resolveDashboardFeatures(recentlyUsedTools, visiblePages),
[recentlyUsedTools, visiblePages],
);
const showRecent = recentFeatures.length > 0;
return { visibleFeatures, recentFeatures, showRecent, navigateTo };
}
@@ -18,14 +18,6 @@ vi.mock('@/components/GlobalSnackbar', () => ({
}), }),
})); }));
vi.mock('@/config/features', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/config/features')>();
return {
...actual,
getEntryPointType: () => 'sidepanel',
};
});
vi.mock('../components/QrCodePreview', () => ({ vi.mock('../components/QrCodePreview', () => ({
default: () => <div data-testid="qr-code-preview">QrCodePreview</div>, default: () => <div data-testid="qr-code-preview">QrCodePreview</div>,
})); }));
+36 -39
View File
@@ -28,10 +28,11 @@ const isValidPage = (page: unknown): page is PageType => {
}; };
/** /**
* 校验页面列表是否合法 * 页面列表中过滤非法项(如已移除的 dashboard),保留合法 PageType
*/ */
const isValidPageList = (pages: unknown): pages is PageType[] => { const sanitizePageList = (pages: unknown): PageType[] | null => {
return Array.isArray(pages) && pages.every(isValidPage); if (!Array.isArray(pages)) return null;
return pages.filter(isValidPage);
}; };
/** /**
@@ -47,6 +48,15 @@ const mergeWithDefaults = (saved: PageType[], defaults: PageType[]): PageType[]
return [...preserved, ...newItems]; return [...preserved, ...newItems];
}; };
/**
* 解析并合并页面列表:过滤非法项后与默认列表合并
*/
const resolvePageList = (pages: unknown, defaults: PageType[]): PageType[] => {
const sanitized = sanitizePageList(pages);
if (sanitized === null) return defaults;
return mergeWithDefaults(sanitized, defaults);
};
interface RouterContextType { interface RouterContextType {
currentPage: PageType; currentPage: PageType;
visiblePages: PageType[]; visiblePages: PageType[];
@@ -54,7 +64,6 @@ interface RouterContextType {
recentlyUsedTools: PageType[]; recentlyUsedTools: PageType[];
isLoaded: boolean; isLoaded: boolean;
navigateTo: (page: PageType) => void; navigateTo: (page: PageType) => void;
goHome: () => void;
setVisiblePages: (pages: PageType[]) => void; setVisiblePages: (pages: PageType[]) => void;
setPageOrder: (pages: PageType[]) => void; setPageOrder: (pages: PageType[]) => void;
} }
@@ -72,7 +81,7 @@ interface RouterProviderProps {
export function RouterProvider({ export function RouterProvider({
children, children,
defaultRoute = 'dashboard', defaultRoute = 'timestamp',
syncRoute = true, syncRoute = true,
syncKey = 'app/currentRoute', syncKey = 'app/currentRoute',
visiblePagesKey = 'app/visiblePages', visiblePagesKey = 'app/visiblePages',
@@ -82,26 +91,19 @@ export function RouterProvider({
getSyncSnapshot(syncKey as string, defaultRoute, isValidPage), getSyncSnapshot(syncKey as string, defaultRoute, isValidPage),
); );
const [visiblePages, setVisiblePages] = useState<PageType[]>(() => { const [visiblePages, setVisiblePages] = useState<PageType[]>(() =>
const snapshot = getSyncSnapshot( resolvePageList(
visiblePagesKey as string, getSyncSnapshot(visiblePagesKey as string, null),
getDefaultVisibleFeatureKeys(), getDefaultVisibleFeatureKeys(),
isValidPageList, ),
); );
return mergeWithDefaults(snapshot, getDefaultVisibleFeatureKeys());
});
const [pageOrder, setPageOrder] = useState<PageType[]>(() => { const [pageOrder, setPageOrder] = useState<PageType[]>(() =>
const snapshot = getSyncSnapshot( resolvePageList(getSyncSnapshot(pageOrderKey as string, null), getDefaultPageOrder()),
pageOrderKey as string,
getDefaultPageOrder(),
isValidPageList,
); );
return mergeWithDefaults(snapshot, getDefaultPageOrder());
});
const [recentlyUsedTools, setRecentlyUsedTools] = useState<PageType[]>(() => const [recentlyUsedTools, setRecentlyUsedTools] = useState<PageType[]>(
getSyncSnapshot('app/recentlyUsedTools', [], isValidPageList), () => sanitizePageList(getSyncSnapshot('app/recentlyUsedTools', null)) ?? [],
); );
const [isLoaded, setIsLoaded] = useState(false); const [isLoaded, setIsLoaded] = useState(false);
@@ -127,14 +129,15 @@ export function RouterProvider({
if (isValidPage(savedRoute) && syncRoute && !hasUserNavigatedRef.current) { if (isValidPage(savedRoute) && syncRoute && !hasUserNavigatedRef.current) {
setCurrentPage(savedRoute); setCurrentPage(savedRoute);
} }
if (isValidPageList(savedVisiblePages)) { if (sanitizePageList(savedVisiblePages) !== null) {
setVisiblePages(mergeWithDefaults(savedVisiblePages, getDefaultVisibleFeatureKeys())); setVisiblePages(resolvePageList(savedVisiblePages, getDefaultVisibleFeatureKeys()));
} }
if (isValidPageList(savedPageOrder) && savedPageOrder.length > 0) { if (sanitizePageList(savedPageOrder) !== null) {
setPageOrder(mergeWithDefaults(savedPageOrder, getDefaultPageOrder())); setPageOrder(resolvePageList(savedPageOrder, getDefaultPageOrder()));
} }
if (isValidPageList(savedRecentTools)) { const sanitizedRecentTools = sanitizePageList(savedRecentTools);
setRecentlyUsedTools(savedRecentTools); if (sanitizedRecentTools !== null) {
setRecentlyUsedTools(sanitizedRecentTools);
} }
canPersistRef.current = true; canPersistRef.current = true;
@@ -250,20 +253,21 @@ export function RouterProvider({
} }
if (changes[visiblePagesKey as string]) { if (changes[visiblePagesKey as string]) {
const newPages = changes[visiblePagesKey as string].newValue; const newPages = changes[visiblePagesKey as string].newValue;
if (isValidPageList(newPages)) { if (sanitizePageList(newPages) !== null) {
setVisiblePages(mergeWithDefaults(newPages, getDefaultVisibleFeatureKeys())); setVisiblePages(resolvePageList(newPages, getDefaultVisibleFeatureKeys()));
} }
} }
if (changes[pageOrderKey as string]) { if (changes[pageOrderKey as string]) {
const newOrder = changes[pageOrderKey as string].newValue; const newOrder = changes[pageOrderKey as string].newValue;
if (isValidPageList(newOrder)) { if (sanitizePageList(newOrder) !== null) {
setPageOrder(mergeWithDefaults(newOrder, getDefaultPageOrder())); setPageOrder(resolvePageList(newOrder, getDefaultPageOrder()));
} }
} }
if (changes['app/recentlyUsedTools']) { if (changes['app/recentlyUsedTools']) {
const newRecent = changes['app/recentlyUsedTools'].newValue; const newRecent = changes['app/recentlyUsedTools'].newValue;
if (isValidPageList(newRecent)) { const sanitizedRecent = sanitizePageList(newRecent);
setRecentlyUsedTools(newRecent); if (sanitizedRecent !== null) {
setRecentlyUsedTools(sanitizedRecent);
} }
} }
if (changes['contextMenu/pendingData']) { if (changes['contextMenu/pendingData']) {
@@ -295,12 +299,6 @@ export function RouterProvider({
}); });
}; };
const goHome = () => {
hasUserNavigatedRef.current = true;
canPersistRef.current = true;
setCurrentPage('dashboard');
};
return ( return (
<RouterContext.Provider <RouterContext.Provider
value={{ value={{
@@ -310,7 +308,6 @@ export function RouterProvider({
recentlyUsedTools, recentlyUsedTools,
isLoaded, isLoaded,
navigateTo, navigateTo,
goHome,
setVisiblePages, setVisiblePages,
setPageOrder, setPageOrder,
}} }}
+79 -34
View File
@@ -63,13 +63,13 @@ describe('RouterProvider', () => {
mockStorageBatch(); mockStorageBatch();
render( render(
<RouterProvider defaultRoute="dashboard"> <RouterProvider defaultRoute="timestamp">
<TestComponent /> <TestComponent />
</RouterProvider>, </RouterProvider>,
); );
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('current-page')).toHaveTextContent('dashboard'); expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
}); });
expect(storageUtil.getMany).toHaveBeenCalledWith([ expect(storageUtil.getMany).toHaveBeenCalledWith([
@@ -82,16 +82,16 @@ describe('RouterProvider', () => {
}); });
it('应该从指定的 syncKey 加载路由', async () => { it('应该从指定的 syncKey 加载路由', async () => {
mockStorageBatch({ 'app/sidepanelRoute': 'timestamp' }); mockStorageBatch({ 'app/popupRoute': 'jwt' });
render( render(
<RouterProvider syncKey="app/sidepanelRoute"> <RouterProvider syncKey="app/popupRoute">
<TestComponent /> <TestComponent />
</RouterProvider>, </RouterProvider>,
); );
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp'); expect(screen.getByTestId('current-page')).toHaveTextContent('jwt');
}); });
}); });
@@ -105,7 +105,7 @@ describe('RouterProvider', () => {
); );
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('current-page')).toHaveTextContent('dashboard'); expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
}); });
const btn = screen.getByTestId('navigate-btn'); const btn = screen.getByTestId('navigate-btn');
@@ -118,31 +118,14 @@ describe('RouterProvider', () => {
expect(storageUtil.set).toHaveBeenCalledWith('app/popupRoute', 'timestamp'); expect(storageUtil.set).toHaveBeenCalledWith('app/popupRoute', 'timestamp');
}); });
it('应该支持独立的标签页路由同步', async () => {
mockStorageBatch({ 'app/tabRoute': 'qrCode' });
render(
<RouterProvider syncKey="app/tabRoute">
<TestComponent />
</RouterProvider>,
);
await waitFor(() => {
expect(screen.getByTestId('current-page')).toHaveTextContent('qrCode');
});
});
it('应该独立支持 visiblePagesKey 和 pageOrderKey,并合并缺失的新功能', async () => { it('应该独立支持 visiblePagesKey 和 pageOrderKey,并合并缺失的新功能', async () => {
mockStorageBatch({ mockStorageBatch({
'app/sidepanelVisiblePages': ['timestamp', 'storageCleaner'], 'app/popupVisiblePages': ['timestamp', 'storageCleaner'],
'app/sidepanelPageOrder': ['storageCleaner', 'timestamp'], 'app/popupPageOrder': ['storageCleaner', 'timestamp'],
}); });
render( render(
<RouterProvider <RouterProvider visiblePagesKey="app/popupVisiblePages" pageOrderKey="app/popupPageOrder">
visiblePagesKey="app/sidepanelVisiblePages"
pageOrderKey="app/sidepanelPageOrder"
>
<TestComponent /> <TestComponent />
</RouterProvider>, </RouterProvider>,
); );
@@ -160,7 +143,6 @@ describe('RouterProvider', () => {
it('应该将旧存储中缺失的新功能自动合并到 visiblePages 和 pageOrder', async () => { it('应该将旧存储中缺失的新功能自动合并到 visiblePages 和 pageOrder', async () => {
const oldVisiblePages = [ const oldVisiblePages = [
'dashboard',
'timestamp', 'timestamp',
'storageCleaner', 'storageCleaner',
'qrCode', 'qrCode',
@@ -192,14 +174,78 @@ describe('RouterProvider', () => {
const visiblePages = screen.getByTestId('visible-pages').textContent!; const visiblePages = screen.getByTestId('visible-pages').textContent!;
const pageOrder = screen.getByTestId('page-order').textContent!; const pageOrder = screen.getByTestId('page-order').textContent!;
expect(visiblePages.startsWith('dashboard,timestamp')).toBe(true); expect(visiblePages.startsWith('timestamp,storageCleaner')).toBe(true);
expect(pageOrder.startsWith('timestamp,storageCleaner')).toBe(true); expect(pageOrder.startsWith('timestamp,storageCleaner')).toBe(true);
}); });
}); });
it('storage 中 dashboard 路由无效时应回退到 timestamp', async () => {
mockStorageBatch({ 'app/popupRoute': 'dashboard' });
render(
<RouterProvider syncKey="app/popupRoute" defaultRoute="timestamp">
<TestComponent />
</RouterProvider>,
);
await waitFor(() => {
expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
});
});
it('storage 列表含 dashboard 时应过滤并保留其余自定义配置', async () => {
mockStorageBatch({
'app/popupVisiblePages': ['dashboard', 'jwt', 'timestamp'],
'app/popupPageOrder': ['jwt', 'dashboard', 'timestamp'],
'app/recentlyUsedTools': ['dashboard', 'jwt'],
});
render(
<RouterProvider visiblePagesKey="app/popupVisiblePages" pageOrderKey="app/popupPageOrder">
<TestComponent />
</RouterProvider>,
);
await waitFor(() => {
const visiblePages = screen.getByTestId('visible-pages').textContent!;
const pageOrder = screen.getByTestId('page-order').textContent!;
expect(visiblePages.startsWith('jwt,timestamp')).toBe(true);
expect(pageOrder.startsWith('jwt,timestamp')).toBe(true);
expect(visiblePages).not.toContain('dashboard');
expect(pageOrder).not.toContain('dashboard');
});
});
it('localStorage 快照含 dashboard 时应过滤并保留其余配置', async () => {
localStorage.setItem(
'snapshot/app/popupVisiblePages',
JSON.stringify(['dashboard', 'jwt', 'timestamp']),
);
localStorage.setItem(
'snapshot/app/popupPageOrder',
JSON.stringify(['jwt', 'dashboard', 'timestamp']),
);
mockStorageBatch();
render(
<RouterProvider visiblePagesKey="app/popupVisiblePages" pageOrderKey="app/popupPageOrder">
<TestComponent />
</RouterProvider>,
);
const visiblePages = screen.getByTestId('visible-pages').textContent!;
const pageOrder = screen.getByTestId('page-order').textContent!;
expect(visiblePages.startsWith('jwt,timestamp')).toBe(true);
expect(pageOrder.startsWith('jwt,timestamp')).toBe(true);
expect(visiblePages).not.toContain('dashboard');
expect(pageOrder).not.toContain('dashboard');
});
it('应该从 localStorage 快照合并缺失的新功能', async () => { it('应该从 localStorage 快照合并缺失的新功能', async () => {
const oldVisiblePages = [ const oldVisiblePages = [
'dashboard',
'timestamp', 'timestamp',
'storageCleaner', 'storageCleaner',
'qrCode', 'qrCode',
@@ -249,7 +295,6 @@ describe('RouterProvider', () => {
.calls[0][0] as (changes: Record<string, { newValue?: unknown }>) => void; .calls[0][0] as (changes: Record<string, { newValue?: unknown }>) => void;
const oldVisiblePages = [ const oldVisiblePages = [
'dashboard',
'timestamp', 'timestamp',
'storageCleaner', 'storageCleaner',
'qrCode', 'qrCode',
@@ -277,7 +322,7 @@ describe('RouterProvider', () => {
const visiblePages = screen.getByTestId('visible-pages').textContent!; const visiblePages = screen.getByTestId('visible-pages').textContent!;
const pageOrder = screen.getByTestId('page-order').textContent!; const pageOrder = screen.getByTestId('page-order').textContent!;
expect(visiblePages.startsWith('dashboard,timestamp')).toBe(true); expect(visiblePages.startsWith('timestamp,storageCleaner')).toBe(true);
expect(pageOrder.startsWith('timestamp,storageCleaner')).toBe(true); expect(pageOrder.startsWith('timestamp,storageCleaner')).toBe(true);
}); });
}); });
@@ -285,7 +330,7 @@ describe('RouterProvider', () => {
it('localStorage 快照过期时,loadInitialData 完成前不应覆盖 chrome.storage', async () => { it('localStorage 快照过期时,loadInitialData 完成前不应覆盖 chrome.storage', async () => {
const staleRoute = 'timestamp'; const staleRoute = 'timestamp';
const correctRoute = 'jsonTools'; const correctRoute = 'jsonTools';
const defaultVisible = ['dashboard', 'timestamp', 'storageCleaner']; const defaultVisible = ['timestamp', 'storageCleaner'];
const defaultOrder = ['timestamp', 'storageCleaner']; const defaultOrder = ['timestamp', 'storageCleaner'];
localStorage.setItem('snapshot/app/currentRoute', JSON.stringify(staleRoute)); localStorage.setItem('snapshot/app/currentRoute', JSON.stringify(staleRoute));
@@ -340,7 +385,7 @@ describe('RouterProvider', () => {
); );
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('current-page')).toHaveTextContent('dashboard'); expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
}); });
expect(storageUtil.set).not.toHaveBeenCalled(); expect(storageUtil.set).not.toHaveBeenCalled();
}); });
@@ -353,7 +398,7 @@ describe('RouterProvider', () => {
(storageUtil.getMany as ReturnType<typeof vi.fn>).mockImplementation(async () => { (storageUtil.getMany as ReturnType<typeof vi.fn>).mockImplementation(async () => {
await getBlocked; await getBlocked;
return { 'app/currentRoute': 'dashboard' }; return { 'app/currentRoute': 'jwt' };
}); });
render( render(
-4
View File
@@ -94,10 +94,6 @@
} }
@layer components { @layer components {
.page-transition-dashboard {
@apply motion-reduce:transition-none;
}
.page-transition-enter { .page-transition-enter {
@apply motion-reduce:transition-none; @apply motion-reduce:transition-none;
animation: tt-page-enter 200ms ease-out; animation: tt-page-enter 200ms ease-out;
+1 -16
View File
@@ -2,7 +2,6 @@
* 应用页面类型定义 * 应用页面类型定义
*/ */
export type PageType = export type PageType =
| 'dashboard' // 仪表盘/首页
| 'timestamp' // 时间戳转换工具 | 'timestamp' // 时间戳转换工具
| 'storageCleaner' // 存储清理工具 | 'storageCleaner' // 存储清理工具
| 'qrCode' // 二维码工具 | 'qrCode' // 二维码工具
@@ -66,14 +65,10 @@ export interface FormMapEntry {
* 定义了所有持久化在客户端的数据结构 * 定义了所有持久化在客户端的数据结构
*/ */
export interface StorageSchema { export interface StorageSchema {
/** RouterProvider 的默认路由键,仅当未显式传入 syncKey 时使用(popup/sidepanel/tab 入口已各自覆盖) */ /** RouterProvider 的默认路由键,仅当未显式传入 syncKey 时使用(popup 入口已覆盖) */
'app/currentRoute': PageType; 'app/currentRoute': PageType;
/** Popup 窗口的当前路由 */ /** Popup 窗口的当前路由 */
'app/popupRoute': PageType; 'app/popupRoute': PageType;
/** 侧边栏的当前路由 */
'app/sidepanelRoute': PageType;
/** 标签页的当前路由 */
'app/tabRoute': PageType;
/** RouterProvider 的默认可见页面列表键,仅当未显式传入 visiblePagesKey 时使用 */ /** RouterProvider 的默认可见页面列表键,仅当未显式传入 visiblePagesKey 时使用 */
'app/visiblePages': PageType[]; 'app/visiblePages': PageType[];
/** RouterProvider 的默认页面排序键,仅当未显式传入 pageOrderKey 时使用 */ /** RouterProvider 的默认页面排序键,仅当未显式传入 pageOrderKey 时使用 */
@@ -82,14 +77,6 @@ export interface StorageSchema {
'app/popupVisiblePages': PageType[]; 'app/popupVisiblePages': PageType[];
/** Popup 窗口页面的显示顺序 */ /** Popup 窗口页面的显示顺序 */
'app/popupPageOrder': PageType[]; 'app/popupPageOrder': PageType[];
/** 侧边栏可见的页面列表 */
'app/sidepanelVisiblePages': PageType[];
/** 侧边栏页面的显示顺序 */
'app/sidepanelPageOrder': PageType[];
/** 标签页可见的页面列表 */
'app/tabVisiblePages': PageType[];
/** 标签页页面的显示顺序 */
'app/tabPageOrder': PageType[];
/** 应用主题配置 */ /** 应用主题配置 */
'app/theme': string; 'app/theme': string;
/** 主题模式偏好(light/dark/system */ /** 主题模式偏好(light/dark/system */
@@ -100,8 +87,6 @@ export interface StorageSchema {
'qrCode/qrExpanded': boolean; 'qrCode/qrExpanded': boolean;
/** 二维码工具中 URL 部分是否展开 */ /** 二维码工具中 URL 部分是否展开 */
'qrCode/urlExpanded': boolean; 'qrCode/urlExpanded': boolean;
/** 搜索历史记录 */
'app/searchHistory': string[];
/** JSON 工具页面当前子模式 */ /** JSON 工具页面当前子模式 */
'jsonTools/pageMode': JsonToolsPageMode; 'jsonTools/pageMode': JsonToolsPageMode;
/** Base64 转换器页面当前子模式 */ /** Base64 转换器页面当前子模式 */
+2 -2
View File
@@ -37,7 +37,7 @@ describe('chromeStorage', () => {
}); });
it('应该支持数组类型值', async () => { it('应该支持数组类型值', async () => {
const pages = ['dashboard', 'timestamp'] as const; const pages = ['timestamp', 'jwt'] as const;
(chrome.storage.local.get as any).mockResolvedValue({ 'app/visiblePages': pages }); (chrome.storage.local.get as any).mockResolvedValue({ 'app/visiblePages': pages });
const result = await storageUtil.get('app/visiblePages'); const result = await storageUtil.get('app/visiblePages');
@@ -126,7 +126,7 @@ describe('chromeStorage', () => {
}); });
it('应该成功设置数组值', async () => { it('应该成功设置数组值', async () => {
const pages: Array<'dashboard' | 'timestamp'> = ['dashboard', 'timestamp']; const pages: Array<'timestamp' | 'jwt'> = ['timestamp', 'jwt'];
await storageUtil.set('app/visiblePages', pages); await storageUtil.set('app/visiblePages', pages);
expect(chrome.storage.local.set).toHaveBeenCalledWith({ 'app/visiblePages': pages }); expect(chrome.storage.local.set).toHaveBeenCalledWith({ 'app/visiblePages': pages });
-25
View File
@@ -1,25 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { openExtensionPage } from '@/utils/chromeTabs';
describe('chromeTabs', () => {
describe('openExtensionPage', () => {
it('应该在新标签页中打开扩展页面', async () => {
await openExtensionPage('popup.html');
expect(chrome.runtime.getURL).toHaveBeenCalledWith('popup.html');
expect(chrome.tabs.create).toHaveBeenCalledWith({
url: 'chrome-extension://test-extension-id/popup.html',
});
});
it('当创建标签页失败时应记录错误', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
(chrome.tabs.create as any).mockRejectedValue(new Error('Tab creation failed'));
await openExtensionPage('popup.html');
expect(consoleSpy).toHaveBeenCalledWith('打开扩展页面失败:', expect.any(Error));
consoleSpy.mockRestore();
});
});
});
+7 -4
View File
@@ -44,18 +44,21 @@ describe('messages', () => {
); );
}); });
it('应该支持带数据的消息发送', async () => { it('应该支持带数据的消息发送', async () => {
const mockSendMessage = await getMockSendMessage(); const mockSendMessage = await getMockSendMessage();
mockSendMessage.mockResolvedValue(undefined); mockSendMessage.mockResolvedValue(undefined);
const mockTab = { id: 456, url: 'https://example.com' }; const mockTab = { id: 456, url: 'https://example.com' };
(chrome.tabs.query as any).mockResolvedValue([mockTab]); (chrome.tabs.query as any).mockResolvedValue([mockTab]);
await sendMessageToContent(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: true }); await sendMessageToContent(MessageAction.CONTEXT_MENU_CLICKED, {
featureKey: 'timestamp',
payload: '1234567890',
});
expect(mockSendMessage).toHaveBeenCalledWith( expect(mockSendMessage).toHaveBeenCalledWith(
MessageAction.SIDE_PANEL_STATE_CHANGED, MessageAction.CONTEXT_MENU_CLICKED,
{ isOpen: true }, { featureKey: 'timestamp', payload: '1234567890' },
456, 456,
); );
}); });
+2 -4
View File
@@ -169,13 +169,11 @@ describe('useStorageState', () => {
}); });
it('加载失败时不应把快照默认值写回 Chrome Storage', async () => { it('加载失败时不应把快照默认值写回 Chrome Storage', async () => {
localStorage.setItem('snapshot/app/searchHistory', JSON.stringify([])); localStorage.setItem('snapshot/qrCode/urlExpanded', JSON.stringify(true));
(storageUtil.get as any).mockRejectedValue(new Error('Storage read failed')); (storageUtil.get as any).mockRejectedValue(new Error('Storage read failed'));
renderHook(() => renderHook(() => useStorageState('qrCode/urlExpanded', false));
useStorageState('app/searchHistory', [], (val): val is string[] => Array.isArray(val)),
);
await waitFor(() => { await waitFor(() => {
expect(storageUtil.set).not.toHaveBeenCalled(); expect(storageUtil.set).not.toHaveBeenCalled();
-23
View File
@@ -1,23 +0,0 @@
/**
* Chrome 标签页相关工具函数
*/
/**
* 在新标签页中打开扩展页面
* @param page - 扩展页面路径(如 'popup.html'
* @param params - 可选的查询参数
*/
export async function openExtensionPage(
page: string,
params?: Record<string, string>,
): Promise<void> {
try {
const url = new URL(chrome.runtime.getURL(page));
if (params) {
Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
}
await chrome.tabs.create({ url: url.toString() });
} catch (error) {
console.error('打开扩展页面失败:', error);
}
}
-2
View File
@@ -1,7 +1,6 @@
import { defineExtensionMessaging } from '@webext-core/messaging'; import { defineExtensionMessaging } from '@webext-core/messaging';
export enum MessageAction { export enum MessageAction {
SIDE_PANEL_STATE_CHANGED = 'sidePanelStateChanged',
CONTEXT_MENU_CLICKED = 'contextMenuClicked', CONTEXT_MENU_CLICKED = 'contextMenuClicked',
RESTORE_RIGHT_CLICK = 'restoreRightClick', RESTORE_RIGHT_CLICK = 'restoreRightClick',
QUERY_RIGHT_CLICK_STATUS = 'queryRightClickStatus', QUERY_RIGHT_CLICK_STATUS = 'queryRightClickStatus',
@@ -20,7 +19,6 @@ export interface ContextMenuClickedPayload {
} }
export interface ProtocolMap { export interface ProtocolMap {
[MessageAction.SIDE_PANEL_STATE_CHANGED](data: { isOpen: boolean }): void;
[MessageAction.CONTEXT_MENU_CLICKED](data: ContextMenuClickedPayload): void; [MessageAction.CONTEXT_MENU_CLICKED](data: ContextMenuClickedPayload): void;
[MessageAction.RESTORE_RIGHT_CLICK](data: undefined): MessageResponse & { restored: boolean }; [MessageAction.RESTORE_RIGHT_CLICK](data: undefined): MessageResponse & { restored: boolean };
[MessageAction.QUERY_RIGHT_CLICK_STATUS]( [MessageAction.QUERY_RIGHT_CLICK_STATUS](
+1 -12
View File
@@ -41,15 +41,7 @@ export default defineConfig({
name: 'Testing Tool', name: 'Testing Tool',
description: 'A tool for testing web applications.', description: 'A tool for testing web applications.',
version_name: undefined, version_name: undefined,
permissions: [ permissions: ['storage', 'clipboardWrite', 'scripting', 'tabs', 'cookies', 'contextMenus'],
'storage',
'clipboardWrite',
'scripting',
'tabs',
'cookies',
'sidePanel',
'contextMenus',
],
host_permissions: ['<all_urls>'], host_permissions: ['<all_urls>'],
icons: { icons: {
'16': 'icon/16.png', '16': 'icon/16.png',
@@ -66,9 +58,6 @@ export default defineConfig({
'48': 'icon/48.png', '48': 'icon/48.png',
}, },
}, },
side_panel: {
default_path: 'entrypoints/sidepanel/index.html',
},
}, },
vite: () => ({ vite: () => ({
plugins: [manualChunksForHtmlOnly()], plugins: [manualChunksForHtmlOnly()],