Compare commits
8 Commits
6589ea3858
...
v1.0.9
| Author | SHA1 | Date | |
|---|---|---|---|
| 06c2a222ab | |||
| b487f71512 | |||
| 43038c5edb | |||
| 9aa7a51f0b | |||
| d21e970f56 | |||
| 1af3b25af8 | |||
| 550f8f82c7 | |||
| 36b6bfd20d |
@@ -669,7 +669,7 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
|
||||
|
||||
### 9.1 功能元数据
|
||||
|
||||
功能名称与描述在 `config/features.tsx` 的 `FEATURES` 数组中定义:
|
||||
功能名称与描述在 `config/featureMeta.ts` 的 `FEATURES` 数组中定义:
|
||||
|
||||
```typescript
|
||||
{
|
||||
@@ -677,10 +677,11 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
|
||||
label: '时间戳转换',
|
||||
description: '日期与时间戳互转',
|
||||
defaultVisible: true,
|
||||
component: TimestampPage,
|
||||
}
|
||||
```
|
||||
|
||||
页面组件通过 `config/pageLoaders/` 按需加载,不在 `FEATURES` 中引用。
|
||||
|
||||
Dashboard 卡片、TopBar 搜索等功能从此处读取 `label` / `description`。
|
||||
|
||||
### 9.2 页面与组件文案
|
||||
|
||||
@@ -5,3 +5,4 @@
|
||||
| 文档 | 状态 | 说明 |
|
||||
| -------------------------------------------------------------------------------- | ----------------- | ---------------------------------------------------- |
|
||||
| [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` 的 feature(dashboard 移除后不应出现)
|
||||
|
||||
### 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. 全局移除 dashboard(PageType → 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 宽度 450px(App.tsx + index.html)
|
||||
- [ ] popup defaultRoute="timestamp"
|
||||
- [ ] 全局移除 dashboard(PageType、FEATURES、pageLoader、页面目录)
|
||||
- [ ] TopBar 移除返回按钮与 goHome 相关逻辑
|
||||
- [ ] RouterProvider 移除 goHome,defaultRoute 改为 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) 为索引。
|
||||
@@ -382,14 +382,14 @@ function loadRule(ruleId: string): void {
|
||||
|
||||
使用 `localStorage`,键名 `testDataGenerator_rules`。API 为**命名导出函数**(见 `src/utils/ruleStorage.ts`):
|
||||
|
||||
| 函数 | 说明 |
|
||||
| ---- | ---- |
|
||||
| `getAll()` / `getById()` / `getByName()` | 读取 |
|
||||
| 函数 | 说明 |
|
||||
| ------------------------------------------------------ | ---------------------------------- |
|
||||
| `getAll()` / `getById()` / `getByName()` | 读取 |
|
||||
| `save()` / `update()` / `deleteRule()` / `duplicate()` | 写入;失败时返回 `null` 或 `false` |
|
||||
| `recordUse()` | 递增 `useCount`、更新 `lastUsedAt` |
|
||||
| `search()` / `getRecent()` | 搜索与最近使用 |
|
||||
| `exportRules()` / `importRules()` | 导入导出 JSON 数组 |
|
||||
| `clear()` | 清空全部规则 |
|
||||
| `recordUse()` | 递增 `useCount`、更新 `lastUsedAt` |
|
||||
| `search()` / `getRecent()` | 搜索与最近使用 |
|
||||
| `exportRules()` / `importRules()` | 导入导出 JSON 数组 |
|
||||
| `clear()` | 清空全部规则 |
|
||||
|
||||
写入失败(如 `QuotaExceededError`)时,内部 `setAll()` 返回 `false`,`save`/`update` 返回 `null`,`deleteRule` 返回 `false`,并在控制台输出 `[ruleStorage] 保存规则失败`。调用方须检查返回值,避免误报成功。
|
||||
|
||||
|
||||
@@ -1505,9 +1505,7 @@ export class DataExporter {
|
||||
```typescript
|
||||
// src/types/testDataGenerator.ts
|
||||
|
||||
type WorkerRequestMessage =
|
||||
| { type: 'start'; payload: WorkerStartPayload }
|
||||
| { type: 'cancel' };
|
||||
type WorkerRequestMessage = { type: 'start'; payload: WorkerStartPayload } | { type: 'cancel' };
|
||||
|
||||
type WorkerResponseMessage =
|
||||
| { type: 'progress'; generationId: number; payload: GenerateProgress }
|
||||
|
||||
@@ -4,30 +4,6 @@
|
||||
* 用于 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) {
|
||||
if (variant === 'tool') {
|
||||
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>
|
||||
);
|
||||
export default function PageSkeleton() {
|
||||
return <ToolPageSkeleton />;
|
||||
}
|
||||
|
||||
PageSkeleton.displayName = 'PageSkeleton';
|
||||
|
||||
+13
-13
@@ -4,20 +4,20 @@
|
||||
|
||||
## 组件列表
|
||||
|
||||
| 组件 | 用途 |
|
||||
| ----------------------- | ------------------------------------------------------------------------------ |
|
||||
| `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界和骨架屏 |
|
||||
| `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 |
|
||||
| `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 |
|
||||
| `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 |
|
||||
| 组件 | 用途 |
|
||||
| ----------------------- | ------------------------------------------------------------------------------------------------------ |
|
||||
| `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界和骨架屏 |
|
||||
| `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 |
|
||||
| `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 |
|
||||
| `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 |
|
||||
| `CopyButton.tsx` | 一键复制按钮:复制成功后 1.5s 内切换为 Check 图标并应用 `text-emerald-500`;空内容/失败时 `toast` 提示 |
|
||||
| `ImageUploader.tsx` | 图片上传组件,支持拖拽上传、文件选择和预览 |
|
||||
| `QrCodePreview.tsx` | 二维码预览组件,展示生成的二维码图片,提供复制和下载操作 |
|
||||
| `DecodeResultPaper.tsx` | Base64 解码结果展示面板,显示 MIME 类型、文件大小、文件名输入和下载按钮 |
|
||||
| `GlobalSnackbar.tsx` | 全局消息提示组件 + Context Provider,支持受控/Hook/全局单例三种使用方式 |
|
||||
| `ErrorBoundary.tsx` | 全局错误边界(类组件),捕获子组件树 JS 错误并展示友好错误页面 |
|
||||
| `PageErrorBoundary.tsx` | 页面级错误边界,适配 shadcn 暗黑模式,支持 `resetKey` 自动恢复 |
|
||||
| `PageSkeleton.tsx` | 页面骨架屏,提供 `dashboard` 和 `tool` 两种变体,用于 Suspense fallback |
|
||||
| `ImageUploader.tsx` | 图片上传组件,支持拖拽上传、文件选择和预览 |
|
||||
| `QrCodePreview.tsx` | 二维码预览组件,展示生成的二维码图片,提供复制和下载操作 |
|
||||
| `DecodeResultPaper.tsx` | Base64 解码结果展示面板,显示 MIME 类型、文件大小、文件名输入和下载按钮 |
|
||||
| `GlobalSnackbar.tsx` | 全局消息提示组件 + Context Provider,支持受控/Hook/全局单例三种使用方式 |
|
||||
| `ErrorBoundary.tsx` | 全局错误边界(类组件),捕获子组件树 JS 错误并展示友好错误页面 |
|
||||
| `PageErrorBoundary.tsx` | 页面级错误边界,适配 shadcn 暗黑模式,支持 `resetKey` 自动恢复 |
|
||||
| `PageSkeleton.tsx` | 页面骨架屏,提供 `dashboard` 和 `tool` 两种变体,用于 Suspense fallback |
|
||||
|
||||
## 使用约定
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ function LoadedPage({ pageKey }: { pageKey: PageType }) {
|
||||
}, [pageKey]);
|
||||
|
||||
if (!Page) {
|
||||
return <PageSkeleton variant={pageKey === 'dashboard' ? 'dashboard' : 'tool'} />;
|
||||
return <PageSkeleton />;
|
||||
}
|
||||
|
||||
return <Page />;
|
||||
@@ -39,9 +39,6 @@ function LoadedPage({ pageKey }: { pageKey: PageType }) {
|
||||
export default function RouterContainer() {
|
||||
const { currentPage } = useRouter();
|
||||
|
||||
const animationClass =
|
||||
currentPage === 'dashboard' ? 'page-transition-dashboard' : 'page-transition-enter';
|
||||
|
||||
const currentFeature = getFeatureByKey(currentPage);
|
||||
|
||||
return (
|
||||
@@ -49,8 +46,7 @@ export default function RouterContainer() {
|
||||
key={currentPage}
|
||||
className={cn(
|
||||
'flex-1 flex flex-col overflow-x-hidden overflow-y-auto',
|
||||
'motion-reduce:transition-none',
|
||||
animationClass,
|
||||
'motion-reduce:transition-none page-transition-enter',
|
||||
)}
|
||||
>
|
||||
<PageErrorBoundary resetKey={currentPage}>
|
||||
|
||||
@@ -4,41 +4,17 @@ import PageSkeleton from '@/components/PageSkeleton';
|
||||
|
||||
describe('PageSkeleton 组件', () => {
|
||||
describe('渲染测试', () => {
|
||||
it('默认应渲染 dashboard 骨架屏', () => {
|
||||
it('应渲染工具页面骨架', () => {
|
||||
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');
|
||||
expect(skeletons.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('布局结构测试', () => {
|
||||
it('dashboard 骨架屏应使用 grid 布局', () => {
|
||||
const { container } = render(<PageSkeleton variant="dashboard" />);
|
||||
const gridContainer = container.firstChild as HTMLElement;
|
||||
|
||||
expect(gridContainer).toHaveClass('grid');
|
||||
});
|
||||
|
||||
it('tool 骨架屏应有内边距', () => {
|
||||
const { container } = render(<PageSkeleton variant="tool" />);
|
||||
it('工具骨架屏应有内边距', () => {
|
||||
const { container } = render(<PageSkeleton />);
|
||||
const toolContainer = container.firstChild as HTMLElement;
|
||||
|
||||
expect(toolContainer).toHaveClass('p-5');
|
||||
@@ -46,16 +22,8 @@ describe('PageSkeleton 组件', () => {
|
||||
});
|
||||
|
||||
describe('骨架屏元素测试', () => {
|
||||
it('dashboard 骨架屏应包含圆角和边框样式', () => {
|
||||
const { container } = render(<PageSkeleton variant="dashboard" />);
|
||||
|
||||
// 获取第一个卡片容器
|
||||
const card = container.querySelector('.rounded-xl.border');
|
||||
expect(card).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('tool 骨架屏应包含动画脉冲效果', () => {
|
||||
const { container } = render(<PageSkeleton variant="tool" />);
|
||||
it('工具骨架屏应包含动画脉冲效果', () => {
|
||||
const { container } = render(<PageSkeleton />);
|
||||
|
||||
const skeletons = container.querySelectorAll('.animate-pulse');
|
||||
expect(skeletons.length).toBeGreaterThan(0);
|
||||
|
||||
@@ -6,12 +6,10 @@ import type { PageType } from '@/types/storage';
|
||||
import React from 'react';
|
||||
|
||||
const mockRouterValue = {
|
||||
currentPage: 'dashboard' as PageType,
|
||||
visiblePages: ['dashboard', 'timestamp'] as PageType[],
|
||||
currentPage: 'timestamp' as PageType,
|
||||
visiblePages: ['timestamp', 'jwt'] as PageType[],
|
||||
pageOrder: ['timestamp'] as PageType[],
|
||||
navigateTo: vi.fn(),
|
||||
syncNavigation: vi.fn(),
|
||||
goHome: vi.fn(),
|
||||
setVisiblePages: vi.fn(),
|
||||
setPageOrder: vi.fn(),
|
||||
recentlyUsedTools: [] as PageType[],
|
||||
@@ -34,21 +32,14 @@ describe('RouterContainer 组件', () => {
|
||||
|
||||
describe('渲染测试', () => {
|
||||
it('mount 后应直接渲染页面结构(不等待 storage 加载)', () => {
|
||||
mockRouterValue.currentPage = 'dashboard';
|
||||
mockRouterValue.currentPage = 'timestamp';
|
||||
const { container } = renderWithProvider(<RouterContainer />);
|
||||
expect(container.querySelector('.page-transition-dashboard')).toBeInTheDocument();
|
||||
expect(container.querySelector('.page-transition-enter')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('动画类测试', () => {
|
||||
it('在 dashboard 页面应应用 dashboard 动画类', () => {
|
||||
mockRouterValue.currentPage = 'dashboard';
|
||||
renderWithProvider(<RouterContainer />);
|
||||
const box = document.querySelector('.page-transition-dashboard');
|
||||
expect(box).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('在非 dashboard 页面应应用 enter 动画类', () => {
|
||||
it('应应用 enter 动画类', () => {
|
||||
mockRouterValue.currentPage = 'timestamp';
|
||||
renderWithProvider(<RouterContainer />);
|
||||
const box = document.querySelector('.page-transition-enter');
|
||||
@@ -60,7 +51,7 @@ describe('RouterContainer 组件', () => {
|
||||
it('currentPage 变化时应更新', () => {
|
||||
const { rerender } = renderWithProvider(<RouterContainer />);
|
||||
|
||||
mockRouterValue.currentPage = 'timestamp';
|
||||
mockRouterValue.currentPage = 'jwt';
|
||||
rerender(<RouterProvider>{<RouterContainer />}</RouterProvider>);
|
||||
|
||||
const box = document.querySelector('.page-transition-enter');
|
||||
@@ -70,11 +61,10 @@ describe('RouterContainer 组件', () => {
|
||||
|
||||
describe('页面级错误隔离', () => {
|
||||
it('PageErrorBoundary 应包裹页面内容', () => {
|
||||
mockRouterValue.currentPage = 'dashboard';
|
||||
mockRouterValue.currentPage = 'timestamp';
|
||||
const { container } = renderWithProvider(<RouterContainer />);
|
||||
|
||||
// 验证 RouterContainer 的 Box 结构存在
|
||||
const routerBox = container.querySelector('.page-transition-dashboard');
|
||||
const routerBox = container.querySelector('.page-transition-enter');
|
||||
expect(routerBox).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,10 +4,6 @@ const pageLoadTracker = vi.hoisted(() => ({
|
||||
loaded: [] as string[],
|
||||
}));
|
||||
|
||||
vi.mock('@/pages/Dashboard', () => {
|
||||
pageLoadTracker.loaded.push('Dashboard');
|
||||
return { default: () => null };
|
||||
});
|
||||
vi.mock('@/pages/Timestamp', () => {
|
||||
pageLoadTracker.loaded.push('Timestamp');
|
||||
return { default: () => null };
|
||||
@@ -63,24 +59,24 @@ describe('features 懒加载', () => {
|
||||
it('访问 FEATURES 元数据时不应加载任何页面模块', async () => {
|
||||
const { FEATURES } = await import('@/config/features');
|
||||
|
||||
expect(FEATURES).toHaveLength(10);
|
||||
expect(FEATURES).toHaveLength(9);
|
||||
expect(pageLoadTracker.loaded).toEqual([]);
|
||||
});
|
||||
|
||||
it('loadPage 应仅加载对应页面模块', async () => {
|
||||
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 () => {
|
||||
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('TestDataGenerator');
|
||||
});
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
|
||||
describe('features', () => {
|
||||
describe('FEATURES', () => {
|
||||
it('应该有10个功能定义', () => {
|
||||
expect(FEATURES).toHaveLength(10);
|
||||
it('应该有9个功能定义', () => {
|
||||
expect(FEATURES).toHaveLength(9);
|
||||
});
|
||||
|
||||
it('应该有每个功能的所有必需属性', () => {
|
||||
@@ -24,12 +24,9 @@ describe('features', () => {
|
||||
expect(typeof feature.label).toBe('string');
|
||||
expect(typeof feature.description).toBe('string');
|
||||
expect(typeof feature.defaultVisible).toBe('boolean');
|
||||
|
||||
if (feature.key !== 'dashboard') {
|
||||
expect(feature).toHaveProperty('icon');
|
||||
expect(feature).toHaveProperty('themeColorKey');
|
||||
expect(typeof feature.themeColorKey).toBe('string');
|
||||
}
|
||||
expect(feature).toHaveProperty('icon');
|
||||
expect(feature).toHaveProperty('themeColorKey');
|
||||
expect(typeof feature.themeColorKey).toBe('string');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,13 +38,6 @@ describe('features', () => {
|
||||
});
|
||||
|
||||
describe('getFeatureByKey', () => {
|
||||
it('应该返回dashboard功能', () => {
|
||||
const feature = getFeatureByKey('dashboard');
|
||||
expect(feature).toBeDefined();
|
||||
expect(feature?.key).toBe('dashboard');
|
||||
expect(feature?.label).toBe('仪表盘');
|
||||
});
|
||||
|
||||
it('应该返回时间戳功能', () => {
|
||||
const feature = getFeatureByKey('timestamp');
|
||||
expect(feature).toBeDefined();
|
||||
@@ -78,9 +68,8 @@ describe('features', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('应该包含仪表盘、时间戳、存储清理、二维码', () => {
|
||||
it('应该包含时间戳、存储清理、二维码', () => {
|
||||
const visibleKeys = getDefaultVisibleFeatureKeys();
|
||||
expect(visibleKeys).toContain('dashboard');
|
||||
expect(visibleKeys).toContain('timestamp');
|
||||
expect(visibleKeys).toContain('storageCleaner');
|
||||
expect(visibleKeys).toContain('qrCode');
|
||||
@@ -90,8 +79,7 @@ describe('features', () => {
|
||||
describe('getAllFeatureKeys', () => {
|
||||
it('应该返回所有功能key', () => {
|
||||
const allKeys = getAllFeatureKeys();
|
||||
expect(allKeys).toHaveLength(10);
|
||||
expect(allKeys).toContain('dashboard');
|
||||
expect(allKeys).toHaveLength(9);
|
||||
expect(allKeys).toContain('timestamp');
|
||||
expect(allKeys).toContain('storageCleaner');
|
||||
expect(allKeys).toContain('qrCode');
|
||||
@@ -105,9 +93,9 @@ describe('features', () => {
|
||||
});
|
||||
|
||||
describe('getDefaultPageOrder', () => {
|
||||
it('应该排除仪表盘从页面顺序', () => {
|
||||
it('应该包含所有工具页面', () => {
|
||||
const pageOrder = getDefaultPageOrder();
|
||||
expect(pageOrder).not.toContain('dashboard');
|
||||
expect(pageOrder).toHaveLength(9);
|
||||
});
|
||||
|
||||
it('应该包含时间戳、存储清理、二维码在页面顺序', () => {
|
||||
@@ -116,10 +104,5 @@ describe('features', () => {
|
||||
expect(pageOrder).toContain('storageCleaner');
|
||||
expect(pageOrder).toContain('qrCode');
|
||||
});
|
||||
|
||||
it('应该有9个项目在页面顺序', () => {
|
||||
const pageOrder = getDefaultPageOrder();
|
||||
expect(pageOrder).toHaveLength(9);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,12 +25,6 @@ export interface FeatureConfig {
|
||||
}
|
||||
|
||||
export const FEATURES: FeatureConfig[] = [
|
||||
{
|
||||
key: 'dashboard',
|
||||
label: '仪表盘',
|
||||
description: '',
|
||||
defaultVisible: true,
|
||||
},
|
||||
{
|
||||
key: 'timestamp',
|
||||
label: '时间戳',
|
||||
@@ -118,5 +112,5 @@ export function getAllFeatureKeys(): PageType[] {
|
||||
}
|
||||
|
||||
export function getDefaultPageOrder(): PageType[] {
|
||||
return FEATURES.filter((f) => f.key !== 'dashboard').map((f) => f.key);
|
||||
return FEATURES.map((f) => f.key);
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { ComponentType } from 'react';
|
||||
|
||||
export default function loadDashboard(): Promise<{ default: ComponentType }> {
|
||||
return import('@/pages/Dashboard');
|
||||
}
|
||||
@@ -16,8 +16,6 @@ function ensurePagesStyles(): Promise<unknown> {
|
||||
export function loadPage(key: PageType): Promise<PageModule> {
|
||||
return ensurePagesStyles().then(() => {
|
||||
switch (key) {
|
||||
case 'dashboard':
|
||||
return import('@/config/pageLoaders/dashboard').then((m) => m.default());
|
||||
case 'timestamp':
|
||||
return import('@/config/pageLoaders/timestamp').then((m) => m.default());
|
||||
case 'storageCleaner':
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
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 flex-col w-[400px] max-w-[400px] min-w-[400px] h-[600px] min-h-[600px] overflow-hidden bg-background">
|
||||
<TopBar />
|
||||
<ErrorBoundary>
|
||||
<RouterContainer />
|
||||
</ErrorBoundary>
|
||||
<div className="flex w-[450px] max-w-[450px] min-w-[450px] h-[600px] min-h-[600px] overflow-hidden bg-background">
|
||||
<div className="flex flex-1 min-w-0 flex-col">
|
||||
<ErrorBoundary>
|
||||
<RouterContainer />
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
<FeatureNav />
|
||||
</div>
|
||||
</RouterProvider>
|
||||
);
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<style>
|
||||
/* Force initial popup size before React hydration */
|
||||
html, body {
|
||||
width: 400px;
|
||||
width: 450px;
|
||||
height: 600px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
+17
-8
@@ -1,14 +1,14 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import * as featureConfig from '@/config/features';
|
||||
import { resolveDashboardFeatures } from '../dashboardFeatures';
|
||||
import { resolveNavFeatures } from '../resolveNavFeatures';
|
||||
|
||||
describe('resolveDashboardFeatures', () => {
|
||||
describe('resolveNavFeatures', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('应按 keys 顺序返回可见工具,并排除 dashboard', () => {
|
||||
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard', 'timestamp', 'jwt']);
|
||||
it('应按 keys 顺序返回可见工具', () => {
|
||||
const items = resolveNavFeatures(['jwt', 'timestamp'], ['timestamp', 'jwt']);
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual(['jwt', 'timestamp']);
|
||||
expect(items.map((item) => item.feature.label)).toEqual(['JWT 解析', '时间戳']);
|
||||
@@ -24,25 +24,34 @@ describe('resolveDashboardFeatures', () => {
|
||||
return feature;
|
||||
});
|
||||
|
||||
const items = resolveDashboardFeatures(['timestamp'], ['dashboard', 'timestamp']);
|
||||
const items = resolveNavFeatures(['timestamp'], ['timestamp']);
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual(['timestamp']);
|
||||
});
|
||||
|
||||
it('应过滤不在 visiblePages 中的工具', () => {
|
||||
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard', 'timestamp']);
|
||||
const items = resolveNavFeatures(['jwt', 'timestamp'], ['timestamp']);
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual(['timestamp']);
|
||||
});
|
||||
|
||||
it('visiblePages 无匹配工具时应返回空列表', () => {
|
||||
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard']);
|
||||
const items = resolveNavFeatures(['jwt', 'timestamp'], []);
|
||||
|
||||
expect(items).toEqual([]);
|
||||
});
|
||||
|
||||
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']);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
+9
-11
@@ -4,23 +4,21 @@
|
||||
|
||||
## 组件列表
|
||||
|
||||
| 目录 | 用途 |
|
||||
| --------- | -------------------------------------------------------------- |
|
||||
| `TopBar/` | 顶部导航栏:搜索(含历史记录)、主题切换、返回导航、标签页打开 |
|
||||
| 目录 | 用途 |
|
||||
| ------------- | ------------------------------------------ |
|
||||
| `FeatureNav/` | 右侧功能导航栏:工具图标切换、底部主题切换 |
|
||||
|
||||
## 目录结构
|
||||
|
||||
遵循与 `pages/` 相同的 UI + Hook 分离模式:
|
||||
|
||||
```
|
||||
layout/TopBar/
|
||||
├── index.tsx # 布局入口
|
||||
├── useTopBar.ts # 业务逻辑 Hook
|
||||
├── constants.ts # 常量
|
||||
├── SearchInput.tsx # 搜索输入框
|
||||
├── SearchDropdown.tsx # 搜索结果/历史下拉面板
|
||||
├── SearchResultItem.tsx # 单条搜索结果项
|
||||
├── TopBarActions.tsx # 右侧操作按钮组
|
||||
layout/FeatureNav/
|
||||
├── index.tsx # 垂直图标导航 + 底部主题按钮
|
||||
├── useFeatureNav.ts # 读路由状态,暴露 navItems / navigateTo
|
||||
├── useThemeToggle.ts # 主题模式循环切换逻辑
|
||||
├── ThemeToggleButton.tsx # 主题切换按钮
|
||||
├── resolveNavFeatures.ts # 功能列表解析
|
||||
└── __tests__/
|
||||
└── index.test.tsx
|
||||
```
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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';
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import { ArrowLeft } 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,
|
||||
goHome,
|
||||
clearSearch,
|
||||
} = useTopBar();
|
||||
|
||||
const actions = [{ id: 'theme', icon: ThemeIcon, title: themeTitle, onClick: cycleThemeMode }];
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,174 +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 { 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;
|
||||
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);
|
||||
|
||||
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,
|
||||
goHome,
|
||||
clearSearch,
|
||||
};
|
||||
}
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -28,10 +28,11 @@ const isValidPage = (page: unknown): page is PageType => {
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验页面列表是否合法
|
||||
* 从页面列表中过滤非法项(如已移除的 dashboard),保留合法 PageType
|
||||
*/
|
||||
const isValidPageList = (pages: unknown): pages is PageType[] => {
|
||||
return Array.isArray(pages) && pages.every(isValidPage);
|
||||
const sanitizePageList = (pages: unknown): PageType[] | null => {
|
||||
if (!Array.isArray(pages)) return null;
|
||||
return pages.filter(isValidPage);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -47,6 +48,15 @@ const mergeWithDefaults = (saved: PageType[], defaults: PageType[]): PageType[]
|
||||
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 {
|
||||
currentPage: PageType;
|
||||
visiblePages: PageType[];
|
||||
@@ -54,7 +64,6 @@ interface RouterContextType {
|
||||
recentlyUsedTools: PageType[];
|
||||
isLoaded: boolean;
|
||||
navigateTo: (page: PageType) => void;
|
||||
goHome: () => void;
|
||||
setVisiblePages: (pages: PageType[]) => void;
|
||||
setPageOrder: (pages: PageType[]) => void;
|
||||
}
|
||||
@@ -72,7 +81,7 @@ interface RouterProviderProps {
|
||||
|
||||
export function RouterProvider({
|
||||
children,
|
||||
defaultRoute = 'dashboard',
|
||||
defaultRoute = 'timestamp',
|
||||
syncRoute = true,
|
||||
syncKey = 'app/currentRoute',
|
||||
visiblePagesKey = 'app/visiblePages',
|
||||
@@ -82,26 +91,19 @@ export function RouterProvider({
|
||||
getSyncSnapshot(syncKey as string, defaultRoute, isValidPage),
|
||||
);
|
||||
|
||||
const [visiblePages, setVisiblePages] = useState<PageType[]>(() => {
|
||||
const snapshot = getSyncSnapshot(
|
||||
visiblePagesKey as string,
|
||||
const [visiblePages, setVisiblePages] = useState<PageType[]>(() =>
|
||||
resolvePageList(
|
||||
getSyncSnapshot(visiblePagesKey as string, null),
|
||||
getDefaultVisibleFeatureKeys(),
|
||||
isValidPageList,
|
||||
);
|
||||
return mergeWithDefaults(snapshot, getDefaultVisibleFeatureKeys());
|
||||
});
|
||||
),
|
||||
);
|
||||
|
||||
const [pageOrder, setPageOrder] = useState<PageType[]>(() => {
|
||||
const snapshot = getSyncSnapshot(
|
||||
pageOrderKey as string,
|
||||
getDefaultPageOrder(),
|
||||
isValidPageList,
|
||||
);
|
||||
return mergeWithDefaults(snapshot, getDefaultPageOrder());
|
||||
});
|
||||
const [pageOrder, setPageOrder] = useState<PageType[]>(() =>
|
||||
resolvePageList(getSyncSnapshot(pageOrderKey as string, null), getDefaultPageOrder()),
|
||||
);
|
||||
|
||||
const [recentlyUsedTools, setRecentlyUsedTools] = useState<PageType[]>(() =>
|
||||
getSyncSnapshot('app/recentlyUsedTools', [], isValidPageList),
|
||||
const [recentlyUsedTools, setRecentlyUsedTools] = useState<PageType[]>(
|
||||
() => sanitizePageList(getSyncSnapshot('app/recentlyUsedTools', null)) ?? [],
|
||||
);
|
||||
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
@@ -127,14 +129,15 @@ export function RouterProvider({
|
||||
if (isValidPage(savedRoute) && syncRoute && !hasUserNavigatedRef.current) {
|
||||
setCurrentPage(savedRoute);
|
||||
}
|
||||
if (isValidPageList(savedVisiblePages)) {
|
||||
setVisiblePages(mergeWithDefaults(savedVisiblePages, getDefaultVisibleFeatureKeys()));
|
||||
if (sanitizePageList(savedVisiblePages) !== null) {
|
||||
setVisiblePages(resolvePageList(savedVisiblePages, getDefaultVisibleFeatureKeys()));
|
||||
}
|
||||
if (isValidPageList(savedPageOrder) && savedPageOrder.length > 0) {
|
||||
setPageOrder(mergeWithDefaults(savedPageOrder, getDefaultPageOrder()));
|
||||
if (sanitizePageList(savedPageOrder) !== null) {
|
||||
setPageOrder(resolvePageList(savedPageOrder, getDefaultPageOrder()));
|
||||
}
|
||||
if (isValidPageList(savedRecentTools)) {
|
||||
setRecentlyUsedTools(savedRecentTools);
|
||||
const sanitizedRecentTools = sanitizePageList(savedRecentTools);
|
||||
if (sanitizedRecentTools !== null) {
|
||||
setRecentlyUsedTools(sanitizedRecentTools);
|
||||
}
|
||||
canPersistRef.current = true;
|
||||
|
||||
@@ -250,20 +253,21 @@ export function RouterProvider({
|
||||
}
|
||||
if (changes[visiblePagesKey as string]) {
|
||||
const newPages = changes[visiblePagesKey as string].newValue;
|
||||
if (isValidPageList(newPages)) {
|
||||
setVisiblePages(mergeWithDefaults(newPages, getDefaultVisibleFeatureKeys()));
|
||||
if (sanitizePageList(newPages) !== null) {
|
||||
setVisiblePages(resolvePageList(newPages, getDefaultVisibleFeatureKeys()));
|
||||
}
|
||||
}
|
||||
if (changes[pageOrderKey as string]) {
|
||||
const newOrder = changes[pageOrderKey as string].newValue;
|
||||
if (isValidPageList(newOrder)) {
|
||||
setPageOrder(mergeWithDefaults(newOrder, getDefaultPageOrder()));
|
||||
if (sanitizePageList(newOrder) !== null) {
|
||||
setPageOrder(resolvePageList(newOrder, getDefaultPageOrder()));
|
||||
}
|
||||
}
|
||||
if (changes['app/recentlyUsedTools']) {
|
||||
const newRecent = changes['app/recentlyUsedTools'].newValue;
|
||||
if (isValidPageList(newRecent)) {
|
||||
setRecentlyUsedTools(newRecent);
|
||||
const sanitizedRecent = sanitizePageList(newRecent);
|
||||
if (sanitizedRecent !== null) {
|
||||
setRecentlyUsedTools(sanitizedRecent);
|
||||
}
|
||||
}
|
||||
if (changes['contextMenu/pendingData']) {
|
||||
@@ -295,12 +299,6 @@ export function RouterProvider({
|
||||
});
|
||||
};
|
||||
|
||||
const goHome = () => {
|
||||
hasUserNavigatedRef.current = true;
|
||||
canPersistRef.current = true;
|
||||
setCurrentPage('dashboard');
|
||||
};
|
||||
|
||||
return (
|
||||
<RouterContext.Provider
|
||||
value={{
|
||||
@@ -310,7 +308,6 @@ export function RouterProvider({
|
||||
recentlyUsedTools,
|
||||
isLoaded,
|
||||
navigateTo,
|
||||
goHome,
|
||||
setVisiblePages,
|
||||
setPageOrder,
|
||||
}}
|
||||
|
||||
@@ -63,13 +63,13 @@ describe('RouterProvider', () => {
|
||||
mockStorageBatch();
|
||||
|
||||
render(
|
||||
<RouterProvider defaultRoute="dashboard">
|
||||
<RouterProvider defaultRoute="timestamp">
|
||||
<TestComponent />
|
||||
</RouterProvider>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('dashboard');
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
|
||||
});
|
||||
|
||||
expect(storageUtil.getMany).toHaveBeenCalledWith([
|
||||
@@ -82,7 +82,7 @@ describe('RouterProvider', () => {
|
||||
});
|
||||
|
||||
it('应该从指定的 syncKey 加载路由', async () => {
|
||||
mockStorageBatch({ 'app/popupRoute': 'timestamp' });
|
||||
mockStorageBatch({ 'app/popupRoute': 'jwt' });
|
||||
|
||||
render(
|
||||
<RouterProvider syncKey="app/popupRoute">
|
||||
@@ -91,7 +91,7 @@ describe('RouterProvider', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('jwt');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -105,7 +105,7 @@ describe('RouterProvider', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('dashboard');
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
|
||||
});
|
||||
|
||||
const btn = screen.getByTestId('navigate-btn');
|
||||
@@ -143,7 +143,6 @@ describe('RouterProvider', () => {
|
||||
|
||||
it('应该将旧存储中缺失的新功能自动合并到 visiblePages 和 pageOrder', async () => {
|
||||
const oldVisiblePages = [
|
||||
'dashboard',
|
||||
'timestamp',
|
||||
'storageCleaner',
|
||||
'qrCode',
|
||||
@@ -175,14 +174,78 @@ describe('RouterProvider', () => {
|
||||
const visiblePages = screen.getByTestId('visible-pages').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);
|
||||
});
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const oldVisiblePages = [
|
||||
'dashboard',
|
||||
'timestamp',
|
||||
'storageCleaner',
|
||||
'qrCode',
|
||||
@@ -232,7 +295,6 @@ describe('RouterProvider', () => {
|
||||
.calls[0][0] as (changes: Record<string, { newValue?: unknown }>) => void;
|
||||
|
||||
const oldVisiblePages = [
|
||||
'dashboard',
|
||||
'timestamp',
|
||||
'storageCleaner',
|
||||
'qrCode',
|
||||
@@ -260,7 +322,7 @@ describe('RouterProvider', () => {
|
||||
const visiblePages = screen.getByTestId('visible-pages').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);
|
||||
});
|
||||
});
|
||||
@@ -268,7 +330,7 @@ describe('RouterProvider', () => {
|
||||
it('localStorage 快照过期时,loadInitialData 完成前不应覆盖 chrome.storage', async () => {
|
||||
const staleRoute = 'timestamp';
|
||||
const correctRoute = 'jsonTools';
|
||||
const defaultVisible = ['dashboard', 'timestamp', 'storageCleaner'];
|
||||
const defaultVisible = ['timestamp', 'storageCleaner'];
|
||||
const defaultOrder = ['timestamp', 'storageCleaner'];
|
||||
|
||||
localStorage.setItem('snapshot/app/currentRoute', JSON.stringify(staleRoute));
|
||||
@@ -323,7 +385,7 @@ describe('RouterProvider', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('dashboard');
|
||||
expect(screen.getByTestId('current-page')).toHaveTextContent('timestamp');
|
||||
});
|
||||
expect(storageUtil.set).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -336,7 +398,7 @@ describe('RouterProvider', () => {
|
||||
|
||||
(storageUtil.getMany as ReturnType<typeof vi.fn>).mockImplementation(async () => {
|
||||
await getBlocked;
|
||||
return { 'app/currentRoute': 'dashboard' };
|
||||
return { 'app/currentRoute': 'jwt' };
|
||||
});
|
||||
|
||||
render(
|
||||
|
||||
@@ -94,10 +94,6 @@
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.page-transition-dashboard {
|
||||
@apply motion-reduce:transition-none;
|
||||
}
|
||||
|
||||
.page-transition-enter {
|
||||
@apply motion-reduce:transition-none;
|
||||
animation: tt-page-enter 200ms ease-out;
|
||||
|
||||
Vendored
-3
@@ -2,7 +2,6 @@
|
||||
* 应用页面类型定义
|
||||
*/
|
||||
export type PageType =
|
||||
| 'dashboard' // 仪表盘/首页
|
||||
| 'timestamp' // 时间戳转换工具
|
||||
| 'storageCleaner' // 存储清理工具
|
||||
| 'qrCode' // 二维码工具
|
||||
@@ -88,8 +87,6 @@ export interface StorageSchema {
|
||||
'qrCode/qrExpanded': boolean;
|
||||
/** 二维码工具中 URL 部分是否展开 */
|
||||
'qrCode/urlExpanded': boolean;
|
||||
/** 搜索历史记录 */
|
||||
'app/searchHistory': string[];
|
||||
/** JSON 工具页面当前子模式 */
|
||||
'jsonTools/pageMode': JsonToolsPageMode;
|
||||
/** Base64 转换器页面当前子模式 */
|
||||
|
||||
+8
-8
@@ -7,8 +7,8 @@
|
||||
| 文件 | 用途 |
|
||||
| ------------------------ | --------------------------------------------------------------------------------------------------- |
|
||||
| `chromeStorage.ts` | Chrome Storage API 封装:类型安全的 `StorageUtils` 类,提供 `get/set/remove` 方法 |
|
||||
| `syncSnapshot.ts` | 通用 `localStorage` 快照读取(`snapshot/{key}`),用于 Router 与 `useStorageState` 首屏防闪烁 |
|
||||
| `themeSnapshot.ts` | 主题专用快照读写与 `document.documentElement` class 切换 |
|
||||
| `syncSnapshot.ts` | 通用 `localStorage` 快照读取(`snapshot/{key}`),用于 Router 与 `useStorageState` 首屏防闪烁 |
|
||||
| `themeSnapshot.ts` | 主题专用快照读写与 `document.documentElement` class 切换 |
|
||||
| `restrictedUrls.ts` | 受限 URL 检测(`chrome://`、`about:` 等),供 Storage Cleaner 等模块复用 |
|
||||
| `chromeTabs.ts` | Chrome Tabs API 封装:获取活动标签页、获取域名、在新标签页打开扩展页面 |
|
||||
| `clipboard.ts` | 剪贴板操作:`copyTextToClipboard`(文本)、`copyImageToClipboard`(图片) |
|
||||
@@ -42,12 +42,12 @@
|
||||
|
||||
写入经内部 `setAll()` 完成;`localStorage.setItem` 抛错(如配额超限)时返回 `false`,并 `console.error`,**不会部分提交**:
|
||||
|
||||
| 方法 | 写入失败返回值 | 常见失败原因 |
|
||||
| ---- | -------------- | ------------ |
|
||||
| `save()` | `null` | 达上限、规则不存在(更新时)、`setItem` 异常 |
|
||||
| `update()` | `null` | 规则不存在、`setItem` 异常 |
|
||||
| `deleteRule()` | `false` | 规则不存在、`setItem` 异常 |
|
||||
| `duplicate()` | 仍可能返回对象但数据未持久化 | 见源码:`duplicate` 未检查 `setAll` 返回值(已知缺口) |
|
||||
| 方法 | 写入失败返回值 | 常见失败原因 |
|
||||
| -------------- | ---------------------------- | ------------------------------------------------------ |
|
||||
| `save()` | `null` | 达上限、规则不存在(更新时)、`setItem` 异常 |
|
||||
| `update()` | `null` | 规则不存在、`setItem` 异常 |
|
||||
| `deleteRule()` | `false` | 规则不存在、`setItem` 异常 |
|
||||
| `duplicate()` | 仍可能返回对象但数据未持久化 | 见源码:`duplicate` 未检查 `setAll` 返回值(已知缺口) |
|
||||
|
||||
调用方应检查返回值后再展示成功 Toast。页面层参考 `FieldList.tsx`:`save`/`update` 返回非空才提示「规则已保存/已更新」。
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ describe('chromeStorage', () => {
|
||||
});
|
||||
|
||||
it('应该支持数组类型值', async () => {
|
||||
const pages = ['dashboard', 'timestamp'] as const;
|
||||
const pages = ['timestamp', 'jwt'] as const;
|
||||
(chrome.storage.local.get as any).mockResolvedValue({ 'app/visiblePages': pages });
|
||||
|
||||
const result = await storageUtil.get('app/visiblePages');
|
||||
@@ -126,7 +126,7 @@ describe('chromeStorage', () => {
|
||||
});
|
||||
|
||||
it('应该成功设置数组值', async () => {
|
||||
const pages: Array<'dashboard' | 'timestamp'> = ['dashboard', 'timestamp'];
|
||||
const pages: Array<'timestamp' | 'jwt'> = ['timestamp', 'jwt'];
|
||||
await storageUtil.set('app/visiblePages', pages);
|
||||
|
||||
expect(chrome.storage.local.set).toHaveBeenCalledWith({ 'app/visiblePages': pages });
|
||||
|
||||
@@ -169,13 +169,11 @@ describe('useStorageState', () => {
|
||||
});
|
||||
|
||||
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'));
|
||||
|
||||
renderHook(() =>
|
||||
useStorageState('app/searchHistory', [], (val): val is string[] => Array.isArray(val)),
|
||||
);
|
||||
renderHook(() => useStorageState('qrCode/urlExpanded', false));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(storageUtil.set).not.toHaveBeenCalled();
|
||||
|
||||
Reference in New Issue
Block a user