feat: 增加商品收藏与多语言聊天建议并完善测试文档

This commit is contained in:
fonghehe 2026-09-17 12:45:34 +08:00
parent 7b1c087c00
commit 9ac24512ea
23 changed files with 1203 additions and 143 deletions

174
README.en.md Normal file
View File

@ -0,0 +1,174 @@
# Vue H5 Template v2
[简体中文](./README.md) | English | [日本語](./README.ja.md)
A Vue 3 engineering template for mobile H5 products. It includes typed requests, OpenAPI type generation, TanStack Query, cancellable streaming AI chat, PWA support, SVG sprites, production image optimization, build-time UI framework selection, and a tested application baseline.
[English documentation](https://sunniejs.github.io/vue-h5-template/en/) · [Migration to v2](https://sunniejs.github.io/vue-h5-template/en/guide/migration-v2)
## Core capabilities
- Vue 3.5, Vite 8 / Rolldown, TypeScript 5.9, Vue Router 4, and Pinia 3.
- TanStack Vue Query for server state; Pinia for client state.
- A typed Axios client with `ApiResponse<T>`, `ApiError`, request IDs, tokens, centralized 401 handling, and timeout/network error normalization.
- `pnpm api:generate` generates backend contract types from the local OpenAPI schema.
- AI chat with POST SSE, `ReadableStream`, `AbortController`, regeneration, retry, Markdown, code blocks, and DOMPurify.
- A storefront with 12+ localized products, search, categories, pull-to-refresh, pagination, product details, cart, and product administration.
- Delivery project management with viewing, creation, editing, deletion, and status filtering; Vite Mock and Gin + PostgreSQL share the contract.
- SVG sprites from `src/assets/icons`, rendered through typed `<SvgIcon />` components.
- One of Vant, NutUI, or Varlet per production build.
- Optional PWA support; the service worker caches the app shell and static images, excluding API requests by default.
- Optional production-only PNG/JPEG/WebP/SVG optimization with Sharp and SVGO.
- Vitest, Vue Test Utils, and Playwright for logic, interaction, and browser coverage.
- Shared typography, spacing, radius, color, control, and motion tokens; mobile bottom navigation becomes compact top navigation on desktop.
- Lazy-loaded Chinese, English, and Japanese translations for content, navigation, and page titles.
- Linting, formatting, Husky, lint-staged, Commitlint, GitHub Actions, and Release Please.
## Quick start
Requires Node.js `>=22.12.0` and pnpm `>=9.12.0`.
```bash
pnpm install
cp .env.example .env.local
pnpm dev
```
Mock APIs are enabled by default. Enter any nonempty username and password to sign in. The engineering examples are available from the third navigation tab. The floating AI button opens `/ai/chat`; the development mock streams SSE chunks from `POST /api/ai/chat`.
You can also open `/shop`, `/shop/cart`, `/examples/request`, and `/examples/workspace` directly. Request examples cover HTTP 400/401/403/404/409, business code 422, server errors, and timeouts. Delivery projects support CRUD in both mock and backend integration modes.
## Common commands
```bash
pnpm lint # Code and style linting
pnpm typecheck # vue-tsc project references
pnpm test # Unit and component tests
pnpm test:coverage # Core coverage thresholds
pnpm test:e2e # Browser flows, responsive layout, and dark mode
pnpm build # Production build
pnpm check # Lint, typecheck, tests, and build
pnpm api:generate # OpenAPI to TypeScript
```
`pnpm check` excludes E2E. CI runs Playwright separately after the main checks.
## Directory boundaries
```text
src/
├── api/ # Axios transport and domain API modules
├── components/ # Reusable UI without route-level responsibilities
├── composables/ # Vue lifecycle and reactive orchestration
├── layout/ # App shell, navigation, and safe areas
├── plugins/ # Application plugins, including Vue Query
├── router/ # Explicit routes, metadata, and guards
├── services/ # Framework-independent providers and transport services
├── store/ # Pinia client state
├── types/ # API, AI, and icon domain types
├── utils/ # Pure helpers without Vue lifecycle dependencies
└── views/ # Lazy-loaded pages
```
See [`AGENTS.md`](./AGENTS.md) for the full contribution rules. It is also the primary repository context for coding agents.
## State management
- Pinia owns sessions, the cart, themes, feature flags, and other client state.
- TanStack Query owns remote data, caching, retries, cancellation, mutations, and pagination.
- `useStreamingChat` owns AI conversation lifecycles. Providers in `services/ai` handle transport; conversation state stays outside Pinia and the query cache.
## API and OpenAPI
Pages consume typed domain modules instead of importing Axios. Narrow errors with `isApiError`; avoid `catch (error: any)`.
To update backend contracts:
1. Update `openapi/schema.yaml`, or change the input URL used by `api:generate`.
2. Run `pnpm api:generate`.
3. Reference generated schemas from `src/types/api/generated.d.ts` in domain API modules.
4. Commit the schema and generated types together so type checking can detect contract drift.
## Favorites and chat suggestions
Product details load the signed-in user’s favorite state with `GET /api/product/favorite?id=1` and save an explicit boolean with `POST /api/product/favorite`. Reads require authentication and only expose public products. Repeated writes are idempotent. The control blocks duplicate submissions and isolates late responses across session changes.
Chat loads `GET /api/ai/suggestions?locale=en-US` from the AI gateway and keeps translated local prompts when offline or when the request fails. Supported locales are `en-US`, `zh-CN`, and `ja-JP`. These prompts make no model calls. The services also expose `/api/v1` aliases.
## AI providers
The provider interface is small and vendor-neutral:
```ts
interface ChatProvider {
chat(
messages: readonly ChatMessage[],
options?: ChatOptions,
): AsyncIterable<ChatChunk>;
}
```
`FetchStreamChatProvider` parses standard SSE. Route OpenAI, Claude, Gemini, or DeepSeek requests through a trusted backend. Provider credentials must stay out of `VITE_*` variables and browser requests. Other stream protocols, including the Vercel AI SDK data stream protocol, can be supported with a provider adapter.
## UI framework selection
```env
VITE_UI_FRAMEWORK=vant # vant | nutui | varlet
```
Vite selects the matching resolver and `#ui-demo` alias. The template includes all three dependencies for project setup, but a production build includes only the selected framework.
Each framework example demonstrates buttons, cells/lists, switches, tags/chips, and progress indicators.
## Internationalization
Translations in `src/locales/langs` cover `zh-CN`, `en-US`, and `ja-JP`. The Home language selector lazy-loads translations and updates content, navigation, route titles, `document.title`, and `<html lang>`. Add new languages to `SUPPORTED_LOCALES` and keep the `common.json` keys synchronized.
## Companion backends
The backend is split into two repositories. The business service (`vue-h5-template-business-service`) owns authentication, users, delivery projects, products, and PostgreSQL. The AI service (`vue-h5-template-ai-service`) owns provider integration, POST SSE, and Redis rate limiting. A parent workspace directory coordinates local Compose development.
```bash
# Terminal 1: PostgreSQL, Gin, FastAPI, and Redis
cd <workspace>/backend/vue-h5-template
docker compose up --build
# Terminal 2: use the committed integration environment
cd <workspace>/frontend/vue-h5-template
pnpm dev:integration
```
Open the address printed by Vite and sign in with `demo / demo1234`. `/shop` reads public products, `/shop/admin/products` manages localized products, and `/examples/workspace` manages delivery projects. `/ai/chat` forwards the same JWT to FastAPI with its SSE request. The backend’s `python3 scripts/smoke.py` checks the Vue proxy, Gin API, PostgreSQL, and FastAPI SSE path.
`pnpm dev` uses frontend mocks and does not require a backend. The documented local Compose database connection is `localhost:5432 / vue_h5_business / vue_h5 / vue_h5_local`; these credentials are for local development only. Each repository’s `docs` branch contains Chinese, English, and Japanese documentation. AI keys belong only in FastAPI configuration.
## PWA and image optimization
```env
VITE_PWA_ENABLED=false
VITE_IMAGE_OPTIMIZE=true
```
PWA support is disabled by default. When enabled, it caches the app shell and static images while excluding `/api`. Image optimization runs only during production builds; disable it when an existing CDN image pipeline already handles your assets.
## Browser and security baseline
The target is iOS Safari 15+, Android Chrome 80+, and modern WeChat/WeCom WebViews. Markdown disables raw HTML and passes through DOMPurify. Redirects accept only internal absolute paths. Production mocks are disabled by default, and the example stores authentication tokens in `sessionStorage`.
Production applications should consider a SameSite, Secure, HttpOnly cookie/BFF approach, with CSP, CSRF protection, and rate limiting at the gateway.
## Documentation and releases
The `docs` branch covers architecture, backend integration, commerce, requests, state, chat, UI, testing, deployment, and v2 migration in all three languages. Release Please maintains versions, the changelog, and GitHub releases from Conventional Commits.
See [`V2_UPGRADE_REPORT.md`](./V2_UPGRADE_REPORT.md) for the upgrade decisions, performance data, breaking changes, and follow-up work.
## Roadmap
- Implemented baseline: authentication, route permissions, error boundaries, network status, system dark theme, lazy routes, sanitized Markdown, PWA/API cache isolation, and engineering checks.
- Add as product needs arise: gateway/JWKS identity, automated Gin OpenAPI export, database backup and rollback, feature flags, analytics/error reporting adapters, uploads, virtual lists, WebView bridges, performance monitoring, and explicit theme switching.
- Optional integrations: QR/camera/Web Share, deep links, SSR/SSG, CDN externals, and native app bridges. Include them only when the product and deployment environment require them.
## License
[MIT](./License)

174
README.ja.md Normal file
View File

@ -0,0 +1,174 @@
# Vue H5 Template v2
[简体中文](./README.md) | [English](./README.en.md) | 日本語
モバイル H5 アプリケーション向けの Vue 3 テンプレートです。型付き API クライアント、OpenAPI からの型生成、TanStack Query、中断可能な AI ストリーミングチャット、PWA、SVG スプライト、本番ビルド時の画像最適化、UI フレームワークの選択、各種テストを備えています。
[日本語ドキュメント](https://sunniejs.github.io/vue-h5-template/ja/) · [v2 への移行](https://sunniejs.github.io/vue-h5-template/ja/guide/migration-v2)
## 主な機能
- Vue 3.5、Vite 8 / Rolldown、TypeScript 5.9、Vue Router 4、Pinia 3。
- サーバーの状態は TanStack Vue Query、クライアントの状態は Pinia で管理。
- `ApiResponse<T>`、`ApiError`、リクエスト ID、トークン、401 の共通処理、タイムアウト・通信エラーの正規化に対応した Axios クライアント。
- `pnpm api:generate` によるローカル OpenAPI スキーマからの型生成。
- POST SSE、`ReadableStream`、`AbortController`、再生成、再試行、Markdown、コードブロック、DOMPurify に対応した AI チャット。
- 12 件以上の多言語商品、検索、カテゴリ、引っ張って更新、ページ分割、商品詳細、カート、商品管理。
- 納品プロジェクトの表示・作成・編集・削除とステータス絞り込み。Vite Mock と Gin + PostgreSQL で API 契約を共有。
- `src/assets/icons` の SVG スプライトと型付き `<SvgIcon />`。
- Vant・NutUI・Varlet から本番ビルドに含めるフレームワークを一つ選択。
- 任意で有効化できる PWA。既定では API をキャッシュせず、アプリシェルと静的画像を対象にする。
- Sharp と SVGO による、本番ビルド時のみの PNG/JPEG/WebP/SVG 最適化。
- Vitest、Vue Test Utils、Playwright によるロジック・操作・ブラウザのテスト。
- 文字、余白、角丸、色、コントロール、アニメーションの共通トークン。デスクトップでは下部ナビゲーションをコンパクトな上部ナビゲーションに切り替え。
- 中国語・英語・日本語の遅延読み込み。本文、ナビゲーション、ページタイトルを同期。
- Lint、フォーマット、Husky、lint-staged、Commitlint、GitHub Actions、Release Please。
## クイックスタート
Node.js `>=22.12.0`、pnpm `>=9.12.0` が必要です。
```bash
pnpm install
cp .env.example .env.local
pnpm dev
```
開発時は既定で Mock API を使います。空でないユーザー名とパスワードでログインできます。三つ目のナビゲーションタブから技術サンプルを開けます。フローティング AI ボタンは `/ai/chat` を開き、開発用 Mock が `POST /api/ai/chat` から SSE を順次返します。
`/shop`、`/shop/cart`、`/examples/request`、`/examples/workspace` にも直接アクセスできます。リクエストのサンプルでは HTTP 400/401/403/404/409、業務エラー 422、サーバーエラー、タイムアウトを確認できます。納品プロジェクトの CRUD は Mock と実バックエンドの両方に対応しています。
## よく使うコマンド
```bash
pnpm lint # コードとスタイルの検査
pnpm typecheck # vue-tsc のプロジェクト参照を検査
pnpm test # 単体・コンポーネントテスト
pnpm test:coverage # コアロジックのカバレッジ検査
pnpm test:e2e # 操作フロー、レスポンシブ表示、ダークモード
pnpm build # 本番ビルド
pnpm check # lint、型検査、テスト、ビルド
pnpm api:generate # OpenAPI から TypeScript を生成
```
`pnpm check` は E2E を含みません。CI では基本検査の後に Playwright を実行します。
## ディレクトリの責務
```text
src/
├── api/ # Axios 通信層とドメイン別 API
├── components/ # ページやルートに依存しない再利用 UI
├── composables/ # Vue のライフサイクルとリアクティブな処理
├── layout/ # アプリシェル、ナビゲーション、セーフエリア
├── plugins/ # Vue Query などのアプリ用プラグイン
├── router/ # 明示的なルート、メタ情報、ガード
├── services/ # フレームワークに依存しないプロバイダーと通信処理
├── store/ # Pinia によるクライアント状態
├── types/ # API、AI、アイコンの型
├── utils/ # Vue のライフサイクルに依存しない純粋関数
└── views/ # 遅延読み込みするページ
```
詳しい開発規約は [`AGENTS.md`](./AGENTS.md) を参照してください。コーディングエージェントもこのファイルを基本の指示として使います。
## 状態管理
- Pinia はログインセッション、カート、テーマ、機能フラグなどを管理します。
- TanStack Query はリモートデータ、キャッシュ、再試行、キャンセル、更新処理、ページ分割を管理します。
- AI の会話ライフサイクルは `useStreamingChat` が管理します。通信は `services/ai` のプロバイダーが担当し、会話状態は Pinia や Query キャッシュに複製しません。
## API と OpenAPI
ページから Axios を直接呼び出さず、型付きのドメイン API を使います。エラーは `isApiError` で絞り込み、`catch (error: any)` は使いません。
バックエンドの契約を更新する手順は次のとおりです。
1. `openapi/schema.yaml`、または `api:generate` の入力 URL を更新します。
2. `pnpm api:generate` を実行します。
3. API モジュールから `src/types/api/generated.d.ts` のスキーマを参照します。
4. スキーマと生成ファイルを一緒にコミットし、型検査で契約の不整合を検出できるようにします。
## お気に入りとチャットの提案
商品詳細は `GET /api/product/favorite?id=1` でログイン中のユーザーのお気に入り状態を取得し、`POST /api/product/favorite` で明示的な真偽値を保存します。取得には認証が必要で、公開商品のみが対象です。同じ書き込みを繰り返しても結果は変わりません。二重送信を防ぎ、アカウント切り替え前の応答を分離します。
チャットは AI ゲートウェイの `GET /api/ai/suggestions?locale=ja-JP` を利用し、通信に失敗した場合は翻訳済みのローカル提案を表示します。対応言語は `en-US`、`zh-CN`、`ja-JP` です。提案の取得でモデルは呼び出しません。両サービスは `/api/v1` にも対応します。
## AI プロバイダー
プロバイダーは特定のベンダーに依存しない、小さなインターフェースです。
```ts
interface ChatProvider {
chat(
messages: readonly ChatMessage[],
options?: ChatOptions,
): AsyncIterable<ChatChunk>;
}
```
既定の `FetchStreamChatProvider` は標準 SSE を解析します。OpenAI、Claude、Gemini、DeepSeek などへのリクエストは信頼できるバックエンドを経由させてください。認証情報を `VITE_*` 変数やブラウザのリクエストに含めないでください。Vercel AI SDK の data stream protocol など、別の形式にはプロバイダーアダプターで対応できます。
## UI フレームワークの選択
```env
VITE_UI_FRAMEWORK=vant # vant | nutui | varlet
```
Vite は選択したフレームワークの resolver と `#ui-demo` エイリアスを使います。テンプレートには三つの依存関係を含めていますが、本番ビルドに入るのは選択したフレームワークだけです。
各フレームワークのサンプルには、ボタン、セル・リスト、スイッチ、タグ・チップ、進捗表示があります。
## 国際化
`src/locales/langs` に `zh-CN`、`en-US`、`ja-JP` の翻訳があります。ホームの言語選択で翻訳を遅延読み込みし、本文、ナビゲーション、ルートタイトル、`document.title`、`<html lang>` を更新します。言語を追加する場合は `SUPPORTED_LOCALES` に登録し、`common.json` のキーをそろえてください。
## 連携するバックエンド
バックエンドは二つのリポジトリに分かれています。業務サービスの `vue-h5-template-business-service` は認証、ユーザー、納品プロジェクト、商品、PostgreSQL を担当します。AI サービスの `vue-h5-template-ai-service` はプロバイダー連携、POST SSE、Redis によるレート制限を担当します。親ワークスペースの Compose 設定でローカル連携環境を起動します。
```bash
# ターミナル 1:PostgreSQL、Gin、FastAPI、Redis を起動
cd <workspace>/backend/vue-h5-template
docker compose up --build
# ターミナル 2:登録済みの連携用環境設定を利用
cd <workspace>/frontend/vue-h5-template
pnpm dev:integration
```
Vite が表示する URL を開き、`demo / demo1234` でログインします。`/shop` は公開商品、`/shop/admin/products` は多言語の商品管理、`/examples/workspace` は納品プロジェクト管理です。`/ai/chat` は同じ JWT を SSE リクエストで FastAPI に送ります。バックエンド側の `python3 scripts/smoke.py` で、Vue のプロキシから Gin、PostgreSQL、FastAPI SSE までの経路を確認できます。
通常の `pnpm dev` はフロントエンドの Mock を使うため、バックエンドは不要です。既存のローカル Compose 設定で案内している DB 接続は `localhost:5432 / vue_h5_business / vue_h5 / vue_h5_local` で、認証情報はローカル開発専用です。各リポジトリの `docs` ブランチには中国語・英語・日本語の開発ドキュメントがあります。AI のキーは FastAPI 側だけに設定します。
## PWA と画像最適化
```env
VITE_PWA_ENABLED=false
VITE_IMAGE_OPTIMIZE=true
```
PWA は既定で無効です。有効にするとアプリシェルと静的画像をキャッシュしますが、`/api` は対象外です。画像最適化は本番ビルド時だけ実行します。CDN 側で既に画像を処理している場合は無効にできます。
## ブラウザとセキュリティ
対象は iOS Safari 15 以降、Android Chrome 80 以降、および現在の WeChat・WeCom WebView です。Markdown の生 HTML を無効にし、DOMPurify でサニタイズします。リダイレクト先はサイト内の絶対パスだけを許可します。本番の Mock は既定で無効です。サンプルの認証トークンは `sessionStorage` に保存します。
本番環境では SameSite・Secure・HttpOnly 属性の Cookie と BFF の構成を検討し、ゲートウェイで CSP、CSRF 対策、レート制限を設定してください。
## ドキュメントとリリース
`docs` ブランチでは、アーキテクチャ、バックエンド連携、商品・購入フロー、API、状態管理、チャット、UI、テスト、デプロイ、v2 移行を三言語で説明しています。Conventional Commits に基づき、Release Please がバージョン、CHANGELOG、GitHub Release を更新します。
更新の判断、性能データ、破壊的変更、今後の作業は [`V2_UPGRADE_REPORT.md`](./V2_UPGRADE_REPORT.md) を参照してください。
## 今後の拡張
- 基本機能として実装済み:認証、ルート権限、エラー境界、通信状態、システム連動のダークテーマ、遅延ルート、安全な Markdown、PWA と API キャッシュの分離、開発・テスト基盤。
- 製品の要件に応じて追加:Gateway/JWKS 認証、Gin OpenAPI の自動出力、DB バックアップとロールバック、機能フラグ、分析・エラー収集アダプター、アップロード、仮想リスト、WebView ブリッジ、性能計測、テーマ切り替え。
- 任意の連携:QR・カメラ・Web Share、ディープリンク、SSR/SSG、CDN 外部化、ネイティブアプリとのブリッジ。製品と配信環境で必要なものだけを導入します。
## ライセンス
[MIT](./License)

View File

@ -1,5 +1,7 @@
# Vue H5 Template v2
简体中文 | [English](./README.en.md) | [日本語](./README.ja.md)
面向真实移动 H5 业务的 Vue 3 工程模板。v2 不是组件库 Playground:它提供类型安全请求、OpenAPI 类型生成、TanStack Query、可中止的 Streaming AI Chat、PWA、SVG Sprite、production 图片优化、单选 UI 框架以及有意义的测试基线。
[在线文档(简体中文)](https://sunniejs.github.io/vue-h5-template/) · [English docs](https://sunniejs.github.io/vue-h5-template/en/) · [日本語ドキュメント](https://sunniejs.github.io/vue-h5-template/ja/) · [迁移到 v2](https://sunniejs.github.io/vue-h5-template/guide/migration-v2)
@ -87,6 +89,10 @@ src/
3. API module 从 `src/types/api/generated.d.ts` 引用 schema;
4. 提交 Schema 与生成文件,让 CI 的 typecheck 检查契约漂移。
## 商品收藏与聊天建议
商品详情通过 `GET /api/product/favorite?id=1` 查询当前用户的收藏状态,通过 `POST /api/product/favorite` 提交明确的布尔状态。查询需要登录,只允许访问公开商品;重复写入保持幂等。收藏控件阻止重复提交,并隔离切换账号后的旧请求。聊天页从 AI 网关读取 `GET /api/ai/suggestions?locale=zh-CN`,离线或失败时保留本地翻译建议。支持 `en-US`、`zh-CN`、`ja-JP`,不会调用模型。两个服务同时支持 `/api/v1` 路径。
## AI Provider
模板采用轻量、供应商无关的接口:

View File

@ -72,7 +72,9 @@ test('mock API returns type-safe server data', async ({ request }) => {
test('AI chat renders streaming chunks and can stop', async ({ page }) => {
await page.goto('/ai/chat');
await page.getByRole('button', { name: '解释这个模板的流式架构' }).click();
await page
.getByRole('button', { name: '解释一下 AI 流式回复是怎么实现的。' })
.click();
await expect(page.getByText(/Vue is a progressive/)).toBeVisible();
const stop = page.getByRole('button', { name: '停止生成' });
if (await stop.isVisible()) await stop.click();
@ -158,3 +160,34 @@ test('delivery workspace supports create, view, edit, filter and delete', async
await row.getByRole('button', { name: '删除' }).click();
await expect(row).toHaveCount(0);
});
test('favorite state survives reload and can be removed', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('用户名').fill('Favorite Tester');
await page.getByLabel('密码').fill('secret');
await page.getByRole('button', { name: '登录', exact: true }).click();
await expect(page).toHaveURL(/\/member$/);
await page.goto('/shop/products/1');
const button = page.locator('.favorite-control button');
await expect(button).toBeEnabled();
await button.click();
await expect(button).toHaveAttribute('aria-pressed', 'true');
await page.reload();
await expect(button).toHaveAttribute('aria-pressed', 'true');
await button.click();
await expect(button).toHaveAttribute('aria-pressed', 'false');
});
test('chat uses server suggestions and falls back offline', async ({
page,
}) => {
await page.goto('/ai/chat');
await expect(
page.getByRole('button', { name: '下单前需要确认哪些信息?' }),
).toBeVisible();
await page.route('**/api/ai/suggestions**', (route) => route.abort());
await page.reload();
await expect(
page.getByRole('button', { name: '解释这个模板的流式架构' }),
).toBeVisible();
});

View File

@ -448,7 +448,62 @@ function success<T>(data: T, requestId?: string) {
return { code: 200, msg: 'ok', data, requestId };
}
const favorites = new Map<string, Set<number>>();
function favoriteResponse(
{ body, query, headers }: MockContext,
write = false,
) {
if (!headers.authorization)
return { code: 401, msg: 'Sign in required', data: null };
const id = Number(write ? body.productId : query.id);
if (!products.some((product) => product.id === id))
return { code: 404, msg: 'Product not found', data: null };
const owner = headers.authorization;
const saved = favorites.get(owner) ?? new Set<number>();
if (write) {
if (typeof body.favorite !== 'boolean')
return { code: 422, msg: 'favorite must be a boolean', data: null };
if (body.favorite) saved.add(id);
else saved.delete(id);
favorites.set(owner, saved);
}
return success({ productId: id, favorite: saved.has(id) });
}
export default [
{
url: '/api/product/favorite',
method: 'get',
response: (context: MockContext) => favoriteResponse(context),
},
{
url: '/api/product/favorite',
method: 'post',
response: (context: MockContext) => favoriteResponse(context, true),
},
{
url: '/api/ai/suggestions',
method: 'get',
response: ({ query }: MockContext) => {
if (query.locale === 'zh-CN')
return success([
'帮我比较商品,看看哪款更适合我。',
'下单前需要确认哪些信息?',
'解释一下 AI 流式回复是怎么实现的。',
]);
if (query.locale === 'ja-JP')
return success([
'商品の比較を手伝ってください。',
'注文前に確認することは?',
'AI のストリーミングの仕組みを教えてください。',
]);
return success([
'Help me compare products before buying.',
'What should I check before placing an order?',
'Explain how streaming AI responses work.',
]);
},
},
{
url: '/api/auth/login',
method: 'post',
@ -459,7 +514,11 @@ export default [
: 'Demo User';
currentUserName = name;
return success(
{ name, token: 'mock-token-v2', expiresIn: 7200 },
{
name,
token: `mock-token-v2-${encodeURIComponent(name)}`,
expiresIn: 7200,
},
headers['x-request-id'],
);
},

View File

@ -5,6 +5,76 @@ info:
servers:
- url: /api
paths:
/ai/suggestions:
get:
operationId: getChatSuggestions
parameters:
- in: query
name: locale
schema:
type: string
enum: [en-US, zh-CN, ja-JP]
default: en-US
responses:
'200':
description: Localized starter prompts without a model call
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/ApiResponse'
- type: object
properties:
data:
type: array
items:
type: string
/product/favorite:
get:
operationId: getFavoriteStatus
security:
- bearerAuth: []
parameters:
- in: query
name: id
required: true
schema:
type: integer
minimum: 1
responses:
'200':
description: Current user's favorite state
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/ApiResponse'
- type: object
properties:
data:
$ref: '#/components/schemas/FavoriteResult'
post:
operationId: setProductFavorite
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/FavoriteRequest'
responses:
'200':
description: Saved favorite state
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/ApiResponse'
- type: object
properties:
data:
$ref: '#/components/schemas/FavoriteResult'
/auth/login:
post:
operationId: login
@ -418,15 +488,36 @@ components:
type: integer
minimum: 1
schemas:
FavoriteRequest:
type: object
required: [productId, favorite]
properties:
productId:
type: integer
minimum: 1
favorite:
type: boolean
FavoriteResult:
type: object
required: [productId, favorite]
properties:
productId:
type: integer
favorite:
type: boolean
ApiResponse:
type: object
required: [code, data, msg]
required: [code, data]
properties:
code:
type: integer
data: {}
msg:
type: string
description: Legacy mock response message
message:
type: string
description: Gin and FastAPI response message
requestId:
type: string
LoginRequest:

View File

@ -5,6 +5,8 @@ import { defineConfig } from 'oxfmt';
* 详见:https://oxc.rs/docs/guide/usage/formatter/config-file-reference.html
*/
export default defineConfig({
// Vite plugins own these declarations; formatting them is overwritten on build.
ignorePatterns: ['types/auto-imports.d.ts', 'types/components.d.ts'],
/**
* 单行长度,适配 prettier 的 80
* Default:100

View File

@ -52,14 +52,17 @@ export function normalizeApiError(error: unknown): ApiError {
});
const { status, data, headers } = axiosError.response;
return new ApiError(data?.msg || axiosError.message || `HTTP ${status}`, {
kind: 'http',
code: data?.code,
status,
requestId: data?.requestId ?? headers['x-request-id'],
details: data,
cause: error,
});
return new ApiError(
data?.msg || data?.message || axiosError.message || `HTTP ${status}`,
{
kind: 'http',
code: data?.code,
status,
requestId: data?.requestId ?? headers['x-request-id'],
details: data,
cause: error,
},
);
}
export const axiosInstance: AxiosInstance = axios.create({
@ -83,14 +86,17 @@ axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
axiosInstance.interceptors.response.use(
(response: AxiosResponse<ApiResponse<unknown>>) => {
const payload = response.data;
if (payload.code < 200 || payload.code >= 300) {
const error = new ApiError(payload.msg || 'Request failed', {
kind: 'business',
code: payload.code,
status: response.status,
requestId: payload.requestId,
details: payload,
});
if (payload.code !== 0 && (payload.code < 200 || payload.code >= 300)) {
const error = new ApiError(
payload.msg || payload.message || 'Request failed',
{
kind: 'business',
code: payload.code,
status: response.status,
requestId: payload.requestId,
details: payload,
},
);
if (payload.code === 401) void runtime.onUnauthorized?.();
return Promise.reject(error);
}

18
src/api/modules/ai.ts Normal file
View File

@ -0,0 +1,18 @@
import { apiClient } from '@/api/client';
// The AI gateway has its own base URL; never send this request to Gin.
export const getChatSuggestions = (
locale: string,
signal?: AbortSignal,
baseURL = '/api/ai',
) =>
apiClient.get<string[]>('/suggestions', {
baseURL,
params: { locale: suggestionLocale(locale) },
signal,
});
function suggestionLocale(locale: string) {
if (locale.startsWith('zh')) return 'zh-CN';
if (locale.startsWith('ja')) return 'ja-JP';
return 'en-US';
}

View File

@ -0,0 +1,10 @@
import { apiClient } from '@/api/client';
import type { components } from '@/types/api/generated';
export type FavoriteResult = components['schemas']['FavoriteResult'];
export const getProductFavorite = (id: number, signal?: AbortSignal) =>
apiClient.get<FavoriteResult>('/product/favorite', {
params: { id },
signal,
});
export const setProductFavorite = (productId: number, favorite: boolean) =>
apiClient.post<FavoriteResult>('/product/favorite', { productId, favorite });

View File

@ -0,0 +1,131 @@
<script setup lang="ts">
import { computed, ref, useId, watch } from 'vue';
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query';
import { RouterLink } from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
getProductFavorite,
setProductFavorite,
} from '@/api/modules/favorites';
const props = defineProps<{ productId: number; session: string }>();
const { t } = useI18n();
const scope = useId();
const generation = ref(0);
const client = useQueryClient();
const key = computed(() => [
'favorite',
scope,
generation.value,
props.productId,
]);
const favorite = useQuery({
queryKey: key,
enabled: computed(
() =>
!!props.session &&
Number.isSafeInteger(props.productId) &&
props.productId > 0,
),
queryFn: ({ signal }) => getProductFavorite(props.productId, signal),
retry: false,
});
const mutation = useMutation({
mutationFn: (input: {
id: number;
favorite: boolean;
key: readonly unknown[];
}) => setProductFavorite(input.id, input.favorite),
onSuccess: (data, input) => {
client.setQueryData(input.key, data);
},
});
watch(
() => props.session,
() => {
generation.value++;
mutation.reset();
},
{ flush: 'sync' },
);
watch(
() => props.productId,
() => mutation.reset(),
);
function toggle() {
if (
!favorite.data.value ||
favorite.isFetching.value ||
mutation.isPending.value
)
return;
mutation.mutate({
id: props.productId,
favorite: !favorite.data.value.favorite,
key: [...key.value],
});
}
</script>
<template>
<div class="favorite-control">
<RouterLink v-if="!session" to="/login">{{
t('common.shop.favoriteLogin')
}}</RouterLink>
<template v-else>
<button
v-if="favorite.isError.value"
type="button"
@click="favorite.refetch()"
>
{{ t('common.global.retry') }}
</button>
<button
v-else
type="button"
:aria-pressed="favorite.data.value?.favorite ?? false"
:disabled="
!favorite.data.value ||
favorite.isFetching.value ||
mutation.isPending.value
"
@click="toggle"
>
{{
t(
favorite.data.value?.favorite
? 'common.shop.unfavorite'
: 'common.shop.favorite',
)
}}
</button>
<p v-if="favorite.isError.value || mutation.isError.value" role="alert">
{{ t('common.shop.favoriteFailed') }}
</p>
</template>
</div>
</template>
<style scoped>
.favorite-control {
margin-block: var(--space-4);
}
.favorite-control button,
.favorite-control a {
display: inline-flex;
align-items: center;
min-height: var(--touch-target);
padding: var(--space-2) var(--space-3);
color: inherit;
background: transparent;
border: 1px solid currentcolor;
border-radius: var(--radius-md);
}
.favorite-control button:disabled {
opacity: 0.5;
}
.favorite-control :focus-visible {
outline: 2px solid currentcolor;
outline-offset: 2px;
}
</style>

View File

@ -182,7 +182,11 @@
"editorLabel": "Product editor",
"operationFailed": "Product operation failed",
"deleteConfirm": "Delete “{name}”?"
}
},
"favorite": "Save product",
"unfavorite": "Remove from favorites",
"favoriteLogin": "Sign in to save products",
"favoriteFailed": "Could not update favorites. Please try again."
},
"cart": {
"eyebrow": "Mobile cart",
@ -257,8 +261,16 @@
"updatedAt": "Updated {date}",
"unknownError": "Project operation failed",
"deleteConfirm": "Delete “{name}”?",
"mode": { "create": "Create", "edit": "Edit", "view": "Project details" },
"status": { "active": "Active", "paused": "Paused", "archived": "Archived" }
"mode": {
"create": "Create",
"edit": "Edit",
"view": "Project details"
},
"status": {
"active": "Active",
"paused": "Paused",
"archived": "Archived"
}
},
"mobile": {
"eyebrow": "MOBILE WEB APIs",
@ -360,7 +372,11 @@
"nextStatus": "Change status",
"delete": "Delete",
"unknownError": "Project operation failed",
"status": { "active": "Active", "paused": "Paused", "archived": "Archived" }
"status": {
"active": "Active",
"paused": "Paused",
"archived": "Archived"
}
},
"ai": {
"open": "AI Assistant",

View File

@ -26,7 +26,12 @@
"login": "ログイン",
"offline": "オフライン"
},
"language": { "label": "言語", "zh": "中国語", "en": "英語", "ja": "日本語" },
"language": {
"label": "言語",
"zh": "中国語",
"en": "英語",
"ja": "日本語"
},
"global": {
"back": "戻る",
"backHome": "ホームへ戻る",
@ -177,7 +182,11 @@
"editorLabel": "商品エディター",
"operationFailed": "商品操作に失敗しました",
"deleteConfirm": "「{name}」を削除しますか?"
}
},
"favorite": "お気に入りに追加",
"unfavorite": "お気に入りから削除",
"favoriteLogin": "ログインして商品を保存",
"favoriteFailed": "お気に入りを更新できませんでした。もう一度お試しください。"
},
"cart": {
"eyebrow": "モバイルカート",
@ -252,7 +261,11 @@
"updatedAt": "{date} 更新",
"unknownError": "プロジェクト操作に失敗しました",
"deleteConfirm": "「{name}」を削除しますか?",
"mode": { "create": "作成", "edit": "編集", "view": "プロジェクト詳細" },
"mode": {
"create": "作成",
"edit": "編集",
"view": "プロジェクト詳細"
},
"status": {
"active": "進行中",
"paused": "一時停止",

View File

@ -26,7 +26,12 @@
"login": "登录",
"offline": "离线"
},
"language": { "label": "语言", "zh": "中文", "en": "英语", "ja": "日语" },
"language": {
"label": "语言",
"zh": "中文",
"en": "英语",
"ja": "日语"
},
"global": {
"back": "返回",
"backHome": "返回首页",
@ -119,7 +124,11 @@
"priceAsc": "价格从低到高",
"priceDesc": "价格从高到低"
},
"status": { "draft": "草稿", "on_sale": "在售", "sold_out": "售罄" },
"status": {
"draft": "草稿",
"on_sale": "在售",
"sold_out": "售罄"
},
"detail": {
"quality": "品质保障",
"shipping": "快速发货",
@ -173,7 +182,11 @@
"editorLabel": "商品编辑器",
"operationFailed": "商品操作失败",
"deleteConfirm": "确定删除“{name}”吗?"
}
},
"favorite": "收藏商品",
"unfavorite": "取消收藏",
"favoriteLogin": "登录后收藏商品",
"favoriteFailed": "收藏更新失败,请重试。"
},
"cart": {
"eyebrow": "移动购物车",
@ -248,8 +261,16 @@
"updatedAt": "更新于 {date}",
"unknownError": "项目操作失败",
"deleteConfirm": "确定删除“{name}”吗?",
"mode": { "create": "新建", "edit": "编辑", "view": "项目详情" },
"status": { "active": "进行中", "paused": "已暂停", "archived": "已归档" }
"mode": {
"create": "新建",
"edit": "编辑",
"view": "项目详情"
},
"status": {
"active": "进行中",
"paused": "已暂停",
"archived": "已归档"
}
},
"mobile": {
"eyebrow": "移动 Web API",
@ -351,7 +372,11 @@
"nextStatus": "切换状态",
"delete": "删除",
"unknownError": "项目操作失败",
"status": { "active": "进行中", "paused": "已暂停", "archived": "已归档" }
"status": {
"active": "进行中",
"paused": "已暂停",
"archived": "已归档"
}
},
"ai": {
"open": "AI 助手",

View File

@ -1,7 +1,8 @@
export interface ApiResponse<T> {
code: number;
data: T;
msg: string;
msg?: string;
message?: string;
requestId?: string;
}

View File

@ -4,6 +4,38 @@
*/
export interface paths {
'/ai/suggestions': {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get: operations['getChatSuggestions'];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
'/product/favorite': {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get: operations['getFavoriteStatus'];
put?: never;
post: operations['setProductFavorite'];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
'/auth/login': {
parameters: {
query?: never;
@ -217,10 +249,21 @@ export interface paths {
export type webhooks = Record<string, never>;
export interface components {
schemas: {
FavoriteRequest: {
productId: number;
favorite: boolean;
};
FavoriteResult: {
productId: number;
favorite: boolean;
};
ApiResponse: {
code: number;
data: unknown;
msg: string;
/** @description Legacy mock response message */
msg?: string;
/** @description Gin and FastAPI response message */
message?: string;
requestId?: string;
};
LoginRequest: {
@ -378,6 +421,80 @@ export interface components {
}
export type $defs = Record<string, never>;
export interface operations {
getChatSuggestions: {
parameters: {
query?: {
locale?: 'en-US' | 'zh-CN' | 'ja-JP';
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Localized starter prompts without a model call */
200: {
headers: {
[name: string]: unknown;
};
content: {
'application/json': components['schemas']['ApiResponse'] & {
data?: string[];
};
};
};
};
};
getFavoriteStatus: {
parameters: {
query: {
id: number;
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Current user's favorite state */
200: {
headers: {
[name: string]: unknown;
};
content: {
'application/json': components['schemas']['ApiResponse'] & {
data?: components['schemas']['FavoriteResult'];
};
};
};
};
};
setProductFavorite: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
'application/json': components['schemas']['FavoriteRequest'];
};
};
responses: {
/** @description Saved favorite state */
200: {
headers: {
[name: string]: unknown;
};
content: {
'application/json': components['schemas']['ApiResponse'] & {
data?: components['schemas']['FavoriteResult'];
};
};
};
};
};
login: {
parameters: {
query?: never;

View File

@ -113,20 +113,37 @@
<script setup lang="ts">
import { computed, nextTick, ref, useTemplateRef, watch } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import { getChatSuggestions } from '@/api/modules/ai';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useStreamingChat } from '@/composables/useStreamingChat';
import { useVisualViewport } from '@/composables/useVisualViewport';
const router = useRouter();
const { t, tm } = useI18n();
const { t, tm, locale } = useI18n();
const { messages, streaming, error, sendMessage, stop, regenerate, clear } =
useStreamingChat();
const { viewportHeight } = useVisualViewport();
const messageList = useTemplateRef<HTMLElement>('messageList');
const showScrollButton = ref(false);
const copiedId = ref('');
const prompts = computed(() => tm('common.ai.prompts') as string[]);
const suggestionsQuery = useQuery({
queryKey: computed(() => ['ai-suggestions', locale.value]),
queryFn: ({ signal }) =>
getChatSuggestions(
locale.value,
signal,
import.meta.env.VITE_AI_API_BASE_URL || '/api/ai',
),
retry: false,
staleTime: 300_000,
});
const prompts = computed(() =>
suggestionsQuery.data.value?.length
? suggestionsQuery.data.value
: (tm('common.ai.prompts') as string[]),
);
const pageStyle = computed(() => ({
height: viewportHeight.value ? `${viewportHeight.value}px` : '100dvh',
}));

View File

@ -42,6 +42,7 @@
><span>{{ t('common.shop.sales', { count: product.sales }) }}</span
><span>{{ t('common.shop.stock', { count: product.stock }) }}</span>
</div>
<FavoriteButton :product-id="productId" :session="user.token" />
</section>
<section class="service-strip">
<span>✓ {{ t('common.shop.detail.quality') }}</span
@ -99,6 +100,8 @@
</template>
<script setup lang="ts">
import FavoriteButton from '@/components/shop/FavoriteButton.vue';
import { useUserStore } from '@/store/modules/user';
import { computed, ref } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import { useI18n } from 'vue-i18n';
@ -115,6 +118,7 @@ const route = useRoute();
const router = useRouter();
const { locale, t } = useI18n();
const cart = useCartStore();
const user = useUserStore();
const productId = computed(() => Number(route.params.id));
const productQuery = useQuery({
queryKey: computed(() => ['products', productId.value]),

View File

@ -81,3 +81,25 @@ describe('api client', () => {
expect(normalizeApiError('bad')).toBeInstanceOf(ApiError);
});
});
it('accepts real service envelopes and preserves their error messages', async () => {
axiosInstance.defaults.adapter = async (config) => ({
data: { code: 0, message: 'ok', data: true },
status: 200,
statusText: 'OK',
headers: new AxiosHeaders(),
config,
});
await expect(apiClient.get('/product/favorite')).resolves.toBe(true);
axiosInstance.defaults.adapter = async (config) => ({
data: { code: 422, message: 'Invalid favorite', data: null },
status: 200,
statusText: 'OK',
headers: new AxiosHeaders(),
config,
});
await expect(apiClient.get('/product/favorite')).rejects.toMatchObject({
message: 'Invalid favorite',
code: 422,
});
});

View File

@ -0,0 +1,52 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
getProductFavorite,
setProductFavorite,
} from '@/api/modules/favorites';
import { getChatSuggestions } from '@/api/modules/ai';
const transport = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() }));
vi.mock('@/api/client', () => ({ apiClient: transport }));
beforeEach(() => {
transport.get.mockReset();
transport.post.mockReset();
});
describe('feature API contracts', () => {
it('forwards bookmark IDs, explicit state and abort signals', async () => {
const signal = new AbortController().signal;
transport.get.mockResolvedValue({ productId: 3, favorite: true });
await expect(getProductFavorite(3, signal)).resolves.toEqual({
productId: 3,
favorite: true,
});
expect(transport.get).toHaveBeenCalledWith('/product/favorite', {
params: { id: 3 },
signal,
});
transport.post.mockResolvedValue({ productId: 3, favorite: false });
await setProductFavorite(3, false);
expect(transport.post).toHaveBeenCalledWith('/product/favorite', {
productId: 3,
favorite: false,
});
});
it.each([
['zh-TW', 'zh-CN'],
['ja-JP', 'ja-JP'],
['de-DE', 'en-US'],
])('normalizes suggestion locale %s', async (input, expected) => {
const signal = new AbortController().signal;
transport.get.mockResolvedValue(['prompt']);
await getChatSuggestions(input, signal, '/custom/ai');
expect(transport.get).toHaveBeenCalledWith('/suggestions', {
baseURL: '/custom/ai',
params: { locale: expected },
signal,
});
});
it('preserves rejected requests for query error recovery', async () => {
const error = new Error('offline');
transport.get.mockRejectedValue(error);
await expect(getChatSuggestions('en-US')).rejects.toBe(error);
await expect(getProductFavorite(1)).rejects.toBe(error);
});
});

View File

@ -0,0 +1,105 @@
import { enableAutoUnmount, mount } from '@vue/test-utils';
import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import FavoriteButton from '@/components/shop/FavoriteButton.vue';
import {
getProductFavorite,
setProductFavorite,
} from '@/api/modules/favorites';
vi.mock('@/api/modules/favorites', () => ({
getProductFavorite: vi.fn(),
setProductFavorite: vi.fn(),
}));
const clients: QueryClient[] = [];
enableAutoUnmount(afterEach);
beforeEach(() => {
vi.mocked(getProductFavorite)
.mockReset()
.mockResolvedValue({ productId: 1, favorite: false });
vi.mocked(setProductFavorite).mockReset();
});
afterEach(() => {
clients.splice(0).forEach((client) => client.clear());
});
function render(session = 'session-a') {
const client = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
clients.push(client);
return mount(FavoriteButton, {
props: { productId: 1, session },
global: {
plugins: [[VueQueryPlugin, { queryClient: client }]],
stubs: { RouterLink: { template: '<a><slot /></a>' } },
},
});
}
describe('favorite interaction', () => {
it('does not request private state before login', () => {
const wrapper = render('');
expect(wrapper.find('a').exists()).toBe(true);
expect(getProductFavorite).not.toHaveBeenCalled();
});
it('loads state, saves and removes a bookmark', async () => {
const wrapper = render();
await vi.waitFor(() =>
expect(wrapper.get('button').attributes('disabled')).toBeUndefined(),
);
expect(getProductFavorite).toHaveBeenCalledWith(1, expect.any(AbortSignal));
vi.mocked(setProductFavorite).mockResolvedValueOnce({
productId: 1,
favorite: true,
});
await wrapper.get('button').trigger('click');
await vi.waitFor(() =>
expect(wrapper.get('button').attributes('aria-pressed')).toBe('true'),
);
vi.mocked(setProductFavorite).mockResolvedValueOnce({
productId: 1,
favorite: false,
});
await wrapper.get('button').trigger('click');
await vi.waitFor(() =>
expect(wrapper.get('button').attributes('aria-pressed')).toBe('false'),
);
expect(setProductFavorite).toHaveBeenLastCalledWith(1, false);
});
it('recovers from a failed read and a failed write without changing the saved state', async () => {
vi.mocked(getProductFavorite).mockRejectedValueOnce(new Error('offline'));
const wrapper = render();
await vi.waitFor(() =>
expect(wrapper.find('[role="alert"]').exists()).toBe(true),
);
await wrapper.get('button').trigger('click');
await vi.waitFor(() =>
expect(wrapper.find('[role="alert"]').exists()).toBe(false),
);
vi.mocked(setProductFavorite).mockRejectedValueOnce(new Error('offline'));
await wrapper.get('button').trigger('click');
await vi.waitFor(() =>
expect(wrapper.find('[role="alert"]').exists()).toBe(true),
);
expect(wrapper.get('button').attributes('aria-pressed')).toBe('false');
});
it('does not overwrite another session when an old write completes', async () => {
let finish!: (value: { productId: number; favorite: boolean }) => void;
vi.mocked(setProductFavorite).mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
}),
);
const wrapper = render();
await vi.waitFor(() =>
expect(wrapper.get('button').attributes('disabled')).toBeUndefined(),
);
await wrapper.get('button').trigger('click');
expect(wrapper.get('button').attributes('disabled')).toBeDefined();
await wrapper.setProps({ session: 'session-b' });
await vi.waitFor(() => expect(getProductFavorite).toHaveBeenCalledTimes(2));
finish({ productId: 1, favorite: true });
await vi.waitFor(() =>
expect(wrapper.get('button').attributes('disabled')).toBeUndefined(),
);
expect(wrapper.get('button').attributes('aria-pressed')).toBe('false');
});
});

View File

@ -8,103 +8,85 @@
// biome-ignore lint: disable
export {}
declare global {
const EffectScope: typeof import('vue').EffectScope;
const acceptHMRUpdate: typeof import('pinia').acceptHMRUpdate;
const computed: typeof import('vue').computed;
const createApp: typeof import('vue').createApp;
const createPinia: typeof import('pinia').createPinia;
const customRef: typeof import('vue').customRef;
const defineAsyncComponent: typeof import('vue').defineAsyncComponent;
const defineComponent: typeof import('vue').defineComponent;
const defineStore: typeof import('pinia').defineStore;
const effectScope: typeof import('vue').effectScope;
const getActivePinia: typeof import('pinia').getActivePinia;
const getCurrentInstance: typeof import('vue').getCurrentInstance;
const getCurrentScope: typeof import('vue').getCurrentScope;
const getCurrentWatcher: typeof import('vue').getCurrentWatcher;
const h: typeof import('vue').h;
const inject: typeof import('vue').inject;
const isProxy: typeof import('vue').isProxy;
const isReactive: typeof import('vue').isReactive;
const isReadonly: typeof import('vue').isReadonly;
const isRef: typeof import('vue').isRef;
const isShallow: typeof import('vue').isShallow;
const mapActions: typeof import('pinia').mapActions;
const mapGetters: typeof import('pinia').mapGetters;
const mapState: typeof import('pinia').mapState;
const mapStores: typeof import('pinia').mapStores;
const mapWritableState: typeof import('pinia').mapWritableState;
const markRaw: typeof import('vue').markRaw;
const nextTick: typeof import('vue').nextTick;
const onActivated: typeof import('vue').onActivated;
const onBeforeMount: typeof import('vue').onBeforeMount;
const onBeforeRouteLeave: typeof import('vue-router').onBeforeRouteLeave;
const onBeforeRouteUpdate: typeof import('vue-router').onBeforeRouteUpdate;
const onBeforeUnmount: typeof import('vue').onBeforeUnmount;
const onBeforeUpdate: typeof import('vue').onBeforeUpdate;
const onDeactivated: typeof import('vue').onDeactivated;
const onErrorCaptured: typeof import('vue').onErrorCaptured;
const onMounted: typeof import('vue').onMounted;
const onRenderTracked: typeof import('vue').onRenderTracked;
const onRenderTriggered: typeof import('vue').onRenderTriggered;
const onScopeDispose: typeof import('vue').onScopeDispose;
const onServerPrefetch: typeof import('vue').onServerPrefetch;
const onUnmounted: typeof import('vue').onUnmounted;
const onUpdated: typeof import('vue').onUpdated;
const onWatcherCleanup: typeof import('vue').onWatcherCleanup;
const provide: typeof import('vue').provide;
const reactive: typeof import('vue').reactive;
const readonly: typeof import('vue').readonly;
const ref: typeof import('vue').ref;
const resolveComponent: typeof import('vue').resolveComponent;
const setActivePinia: typeof import('pinia').setActivePinia;
const setMapStoreSuffix: typeof import('pinia').setMapStoreSuffix;
const shallowReactive: typeof import('vue').shallowReactive;
const shallowReadonly: typeof import('vue').shallowReadonly;
const shallowRef: typeof import('vue').shallowRef;
const storeToRefs: typeof import('pinia').storeToRefs;
const toRaw: typeof import('vue').toRaw;
const toRef: typeof import('vue').toRef;
const toRefs: typeof import('vue').toRefs;
const toValue: typeof import('vue').toValue;
const triggerRef: typeof import('vue').triggerRef;
const unref: typeof import('vue').unref;
const useAttrs: typeof import('vue').useAttrs;
const useCssModule: typeof import('vue').useCssModule;
const useCssVars: typeof import('vue').useCssVars;
const useId: typeof import('vue').useId;
const useLink: typeof import('vue-router').useLink;
const useModel: typeof import('vue').useModel;
const useRoute: typeof import('vue-router').useRoute;
const useRouter: typeof import('vue-router').useRouter;
const useSlots: typeof import('vue').useSlots;
const useTemplateRef: typeof import('vue').useTemplateRef;
const watch: typeof import('vue').watch;
const watchEffect: typeof import('vue').watchEffect;
const watchPostEffect: typeof import('vue').watchPostEffect;
const watchSyncEffect: typeof import('vue').watchSyncEffect;
const EffectScope: typeof import('vue').EffectScope
const acceptHMRUpdate: typeof import('pinia').acceptHMRUpdate
const computed: typeof import('vue').computed
const createApp: typeof import('vue').createApp
const createPinia: typeof import('pinia').createPinia
const customRef: typeof import('vue').customRef
const defineAsyncComponent: typeof import('vue').defineAsyncComponent
const defineComponent: typeof import('vue').defineComponent
const defineStore: typeof import('pinia').defineStore
const effectScope: typeof import('vue').effectScope
const getActivePinia: typeof import('pinia').getActivePinia
const getCurrentInstance: typeof import('vue').getCurrentInstance
const getCurrentScope: typeof import('vue').getCurrentScope
const getCurrentWatcher: typeof import('vue').getCurrentWatcher
const h: typeof import('vue').h
const inject: typeof import('vue').inject
const isProxy: typeof import('vue').isProxy
const isReactive: typeof import('vue').isReactive
const isReadonly: typeof import('vue').isReadonly
const isRef: typeof import('vue').isRef
const isShallow: typeof import('vue').isShallow
const mapActions: typeof import('pinia').mapActions
const mapGetters: typeof import('pinia').mapGetters
const mapState: typeof import('pinia').mapState
const mapStores: typeof import('pinia').mapStores
const mapWritableState: typeof import('pinia').mapWritableState
const markRaw: typeof import('vue').markRaw
const nextTick: typeof import('vue').nextTick
const onActivated: typeof import('vue').onActivated
const onBeforeMount: typeof import('vue').onBeforeMount
const onBeforeRouteLeave: typeof import('vue-router').onBeforeRouteLeave
const onBeforeRouteUpdate: typeof import('vue-router').onBeforeRouteUpdate
const onBeforeUnmount: typeof import('vue').onBeforeUnmount
const onBeforeUpdate: typeof import('vue').onBeforeUpdate
const onDeactivated: typeof import('vue').onDeactivated
const onErrorCaptured: typeof import('vue').onErrorCaptured
const onMounted: typeof import('vue').onMounted
const onRenderTracked: typeof import('vue').onRenderTracked
const onRenderTriggered: typeof import('vue').onRenderTriggered
const onScopeDispose: typeof import('vue').onScopeDispose
const onServerPrefetch: typeof import('vue').onServerPrefetch
const onUnmounted: typeof import('vue').onUnmounted
const onUpdated: typeof import('vue').onUpdated
const onWatcherCleanup: typeof import('vue').onWatcherCleanup
const provide: typeof import('vue').provide
const reactive: typeof import('vue').reactive
const readonly: typeof import('vue').readonly
const ref: typeof import('vue').ref
const resolveComponent: typeof import('vue').resolveComponent
const setActivePinia: typeof import('pinia').setActivePinia
const setMapStoreSuffix: typeof import('pinia').setMapStoreSuffix
const shallowReactive: typeof import('vue').shallowReactive
const shallowReadonly: typeof import('vue').shallowReadonly
const shallowRef: typeof import('vue').shallowRef
const storeToRefs: typeof import('pinia').storeToRefs
const toRaw: typeof import('vue').toRaw
const toRef: typeof import('vue').toRef
const toRefs: typeof import('vue').toRefs
const toValue: typeof import('vue').toValue
const triggerRef: typeof import('vue').triggerRef
const unref: typeof import('vue').unref
const useAttrs: typeof import('vue').useAttrs
const useCssModule: typeof import('vue').useCssModule
const useCssVars: typeof import('vue').useCssVars
const useId: typeof import('vue').useId
const useLink: typeof import('vue-router').useLink
const useModel: typeof import('vue').useModel
const useRoute: typeof import('vue-router').useRoute
const useRouter: typeof import('vue-router').useRouter
const useSlots: typeof import('vue').useSlots
const useTemplateRef: typeof import('vue').useTemplateRef
const watch: typeof import('vue').watch
const watchEffect: typeof import('vue').watchEffect
const watchPostEffect: typeof import('vue').watchPostEffect
const watchSyncEffect: typeof import('vue').watchSyncEffect
}
// for type re-export
declare global {
// @ts-ignore
export type {
Component,
Slot,
Slots,
ComponentPublicInstance,
ComputedRef,
DirectiveBinding,
ExtractDefaultPropTypes,
ExtractPropTypes,
ExtractPublicPropTypes,
InjectionKey,
PropType,
Ref,
ShallowRef,
MaybeRef,
MaybeRefOrGetter,
VNode,
WritableComputedRef,
} from 'vue';
import('vue');
export type { Component, Slot, Slots, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, ShallowRef, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
import('vue')
}

26
types/components.d.ts vendored
View File

@ -5,15 +5,16 @@
// ------
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
import { GlobalComponents } from 'vue';
import { GlobalComponents } from 'vue'
export {};
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
AppErrorBoundary: typeof import('./../src/components/common/AppErrorBoundary.vue')['default']
ChatComposer: typeof import('./../src/components/ai/ChatComposer.vue')['default']
FavoriteButton: typeof import('./../src/components/shop/FavoriteButton.vue')['default']
LoginForm: typeof import('./../src/components/auth/LoginForm.vue')['default']
ProductCard: typeof import('./../src/components/shop/ProductCard.vue')['default']
ProductEditor: typeof import('./../src/components/shop/ProductEditor.vue')['default']
@ -26,13 +27,14 @@ declare module 'vue' {
// For TSX support
declare global {
const AppErrorBoundary: (typeof import('./../src/components/common/AppErrorBoundary.vue'))['default'];
const ChatComposer: (typeof import('./../src/components/ai/ChatComposer.vue'))['default'];
const LoginForm: (typeof import('./../src/components/auth/LoginForm.vue'))['default'];
const ProductCard: (typeof import('./../src/components/shop/ProductCard.vue'))['default'];
const ProductEditor: (typeof import('./../src/components/shop/ProductEditor.vue'))['default'];
const RouterLink: (typeof import('vue-router'))['RouterLink'];
const RouterView: (typeof import('vue-router'))['RouterView'];
const SafeMarkdown: (typeof import('./../src/components/ai/SafeMarkdown.vue'))['default'];
const SvgIcon: (typeof import('./../src/components/common/SvgIcon.vue'))['default'];
}
const AppErrorBoundary: typeof import('./../src/components/common/AppErrorBoundary.vue')['default']
const ChatComposer: typeof import('./../src/components/ai/ChatComposer.vue')['default']
const FavoriteButton: typeof import('./../src/components/shop/FavoriteButton.vue')['default']
const LoginForm: typeof import('./../src/components/auth/LoginForm.vue')['default']
const ProductCard: typeof import('./../src/components/shop/ProductCard.vue')['default']
const ProductEditor: typeof import('./../src/components/shop/ProductEditor.vue')['default']
const RouterLink: typeof import('vue-router')['RouterLink']
const RouterView: typeof import('vue-router')['RouterView']
const SafeMarkdown: typeof import('./../src/components/ai/SafeMarkdown.vue')['default']
const SvgIcon: typeof import('./../src/components/common/SvgIcon.vue')['default']
}