first commit
Some checks failed
Deploy to Aliyun ACR / build-and-push (push) Has been cancelled

This commit is contained in:
jeremygan2021
2026-02-27 17:01:55 +08:00
commit 99218d9035
37 changed files with 15001 additions and 0 deletions

1
.env Normal file
View File

@@ -0,0 +1 @@
VITE_API_KEY=sk-657968d48d0249099f3809f796f80a4f

49
.github/workflows/deploy.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
name: Deploy to Aliyun ACR
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Aliyun Container Registry
uses: docker/login-action@v2
with:
registry: registry.cn-hangzhou.aliyuncs.com
username: ${{ secrets.ALIYUN_ACR_USERNAME }}
password: ${{ secrets.ALIYUN_ACR_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: |
registry.cn-hangzhou.aliyuncs.com/my-namespace/wx-pyq:latest
registry.cn-hangzhou.aliyuncs.com/my-namespace/wx-pyq:${{ github.sha }}
# Optional: Trigger deployment (e.g., via SSH, Kubernetes, or Serverless App Engine)
# - name: Deploy to Server
# uses: appleboy/ssh-action@master
# with:
# host: ${{ secrets.SERVER_HOST }}
# username: ${{ secrets.SERVER_USER }}
# key: ${{ secrets.SSH_PRIVATE_KEY }}
# script: |
# docker pull registry.cn-hangzhou.aliyuncs.com/my-namespace/wx-pyq:latest
# docker stop wx-pyq || true
# docker rm wx-pyq || true
# docker run -d --name wx-pyq -p 80:80 registry.cn-hangzhou.aliyuncs.com/my-namespace/wx-pyq:latest

24
.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

5
.trae/rules/project.md Normal file
View File

@@ -0,0 +1,5 @@
这是一个AI生成朋友圈文案的小项目
用react框架
前端页面
有docker compose文件
没有后端

23
Dockerfile Normal file
View File

@@ -0,0 +1,23 @@
# Build Stage
FROM node:18-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production Stage
FROM nginx:alpine
# Copy built assets from builder stage
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy custom nginx config if needed (using default for now)
# COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

78
README.md Normal file
View File

@@ -0,0 +1,78 @@
# WeChat Moments Generator / 朋友圈文案生成器
Use AI (DashScope Qwen) to generate authentic WeChat Moments copy instantly.
利用 AI (通义千问) 一键生成符合朋友圈风格的文案。
## Features / 功能特性
- **User Page / 用户主页**:
- Simple input for name. / 仅需输入姓名。
- One-click generation. / 一键生成。
- Copy to clipboard. / 支持一键复制。
- Dark mode support. / 支持暗色模式。
- Mobile-first responsive design. / 移动端优先的响应式设计。
- **Admin Dashboard / 管理后台**:
- Manage prompt templates. / 管理提示词模板。
- Real-time preview. / 实时预览生成效果。
- Simulated RBAC (Frontend only). / 模拟权限控制(仅前端)。
## Tech Stack / 技术栈
- **Frontend**: React 18, TypeScript, Vite
- **UI**: Ant Design Mobile, Tailwind CSS
- **State**: Zustand (Persisted to LocalStorage)
- **API**: Axios (Direct call to DashScope API)
- **DevOps**: Docker, GitHub Actions
## Setup / 快速开始
1. **Clone the repository**
```bash
git clone https://github.com/your-username/wx-pyq.git
cd wx-pyq
```
2. **Install dependencies**
```bash
npm install
```
3. **Configure Environment Variables**
Create a `.env` file in the root directory:
```env
VITE_API_KEY=your_dashscope_api_key_here
```
4. **Start Development Server**
```bash
npm run dev
```
5. **Build for Production**
```bash
npm run build
```
## Admin Access / 管理员入口
- URL: `/login` or link from footer.
- Default Credentials:
- Username: `admin`
- Password: `admin123`
## Docker Deployment / Docker 部署
```bash
docker build -t wx-pyq .
docker run -p 80:80 wx-pyq
```
## Note / 注意事项
- This is a frontend-only demo. The API Key is exposed in the browser network requests. For production, please use a backend proxy.
- 本项目为纯前端演示。API Key 会暴露在浏览器请求中。生产环境请务必使用后端代理。
## License
MIT

10
cypress.config.ts Normal file
View File

@@ -0,0 +1,10 @@
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:5173',
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
});

38
cypress/e2e/spec.cy.ts Normal file
View File

@@ -0,0 +1,38 @@
describe('WeChat Moments Generator', () => {
beforeEach(() => {
cy.visit('/');
});
it('should render the home page', () => {
cy.contains('朋友圈神器');
cy.get('input[placeholder*="名字"]').should('be.visible');
cy.contains('立即生成').should('be.visible');
});
it('should require name input', () => {
cy.contains('立即生成').click();
cy.contains('请输入姓名').should('be.visible');
});
// Mock API for full test
it('should generate copy (mocked)', () => {
cy.intercept('POST', '**/chat/completions', {
statusCode: 200,
body: {
choices: [{ message: { content: 'Mocked Result' } }]
}
}).as('generateAPI');
cy.get('input[placeholder*="名字"]').type('TestUser');
cy.contains('立即生成').click();
cy.wait('@generateAPI');
cy.contains('Mocked Result').should('be.visible');
});
it('should navigate to admin login', () => {
cy.contains('Admin Login').click();
cy.url().should('include', '/login');
cy.contains('管理员登录').should('be.visible');
});
});

23
eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>wx_pyq</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

27
jest.config.ts Normal file
View File

@@ -0,0 +1,27 @@
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
moduleNameMapper: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
'\\.(jpg|jpeg|png|gif|webp|svg)$': '<rootDir>/src/__mocks__/fileMock.js',
},
transform: {
'^.+\\.tsx?$': ['ts-jest', {
useESM: true,
tsconfig: 'tsconfig.test.json',
diagnostics: {
ignoreCodes: [1343]
},
astTransformers: {
before: [
{
path: 'ts-jest-mock-import-meta',
options: { metaObjectReplacement: { env: { VITE_API_KEY: 'test-key' } } }
}
]
}
}],
},
extensionsToTreatAsEsm: ['.ts', '.tsx'],
};

13162
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

55
package.json Normal file
View File

@@ -0,0 +1,55 @@
{
"name": "wx_pyq",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"test": "jest",
"test:e2e": "cypress open"
},
"dependencies": {
"antd-mobile": "^5.35.0",
"autoprefixer": "^10.4.19",
"axios": "^1.7.2",
"classnames": "^2.5.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.11",
"framer-motion": "^12.34.3",
"html2canvas": "^1.4.1",
"lucide-react": "^0.395.0",
"postcss": "^8.4.38",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.23.1",
"tailwind-merge": "^2.3.0",
"tailwindcss": "^3.4.4",
"zustand": "^4.5.2"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@types/jest": "^29.5.14",
"@types/node": "^20.14.2",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^7.13.0",
"@typescript-eslint/parser": "^7.13.0",
"@vitejs/plugin-react": "^4.3.1",
"cypress": "^13.11.0",
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"ts-jest": "^29.2.6",
"ts-jest-mock-import-meta": "^1.3.1",
"ts-node": "^10.9.2",
"typescript": "^5.2.2",
"vite": "^5.3.1"
}
}

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

1
public/vite.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

42
src/App.css Normal file
View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

58
src/App.tsx Normal file
View File

@@ -0,0 +1,58 @@
import React, { useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { Home } from './pages/Home';
import { AdminLogin } from './pages/AdminLogin';
import { AdminDashboard } from './pages/AdminDashboard';
import { useAppStore } from './store/useAppStore';
import { ConfigProvider } from 'antd-mobile';
import zhCN from 'antd-mobile/es/locales/zh-CN';
// Protected Route Component
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { admin } = useAppStore();
const location = useLocation();
if (!admin.isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return <>{children}</>;
};
function App() {
const { preferences } = useAppStore();
useEffect(() => {
// Apply initial theme
const root = window.document.documentElement;
if (preferences.theme === 'dark' || (preferences.theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
}, [preferences.theme]);
return (
<ConfigProvider locale={zhCN}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<AdminLogin />} />
<Route
path="/admin"
element={
<ProtectedRoute>
<AdminDashboard />
</ProtectedRoute>
}
/>
{/* Redirect legacy /admin/dashboard to /admin if needed, or just keep structure simple */}
<Route path="/admin/dashboard" element={<Navigate to="/admin" replace />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
</ConfigProvider>
);
}
export default App;

View File

@@ -0,0 +1 @@
module.exports = 'test-file-stub';

1
src/assets/react.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

44
src/components/Header.tsx Normal file
View File

@@ -0,0 +1,44 @@
import React from 'react';
import { NavBar, Space, Switch } from 'antd-mobile';
import { Moon, Sun, Sparkles } from 'lucide-react';
import { useAppStore } from '../store/useAppStore';
import { useNavigate } from 'react-router-dom';
export const Header: React.FC<{ title?: string; showBack?: boolean }> = ({ title = '朋友圈文案生成', showBack = false }) => {
const { preferences, setTheme } = useAppStore();
const navigate = useNavigate();
const toggleTheme = (checked: boolean) => {
setTheme(checked ? 'dark' : 'light');
};
return (
<div className="sticky top-0 z-50 bg-white/40 dark:bg-slate-900/40 backdrop-blur-xl border-b border-white/20 dark:border-white/5">
<NavBar
back={showBack ? '返回' : null}
onBack={showBack ? () => navigate(-1) : undefined}
right={
<Space align="center" className="bg-slate-100/50 dark:bg-slate-800/50 px-3 py-1 rounded-full border border-white/20">
{preferences.theme === 'dark' ? <Moon size={16} className="text-indigo-400" /> : <Sun size={16} className="text-amber-500" />}
<Switch
checked={preferences.theme === 'dark'}
onChange={toggleTheme}
style={{
'--checked-color': '#6366f1',
'--height': '20px',
'--width': '36px'
}}
/>
</Space>
}
>
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-gradient-to-tr from-indigo-600 to-violet-600 flex items-center justify-center shadow-lg shadow-indigo-500/20">
<Sparkles size={16} color="white" />
</div>
<span className="font-bold text-slate-800 dark:text-white tracking-tight">{title}</span>
</div>
</NavBar>
</div>
);
};

52
src/components/Layout.tsx Normal file
View File

@@ -0,0 +1,52 @@
import React, { useEffect } from 'react';
import { useAppStore } from '../store/useAppStore';
import clsx from 'clsx';
import { motion } from 'framer-motion';
interface LayoutProps {
children: React.ReactNode;
className?: string;
}
export const Layout: React.FC<LayoutProps> = ({ children, className }) => {
const { preferences } = useAppStore();
// Handle Dark Mode
useEffect(() => {
const root = window.document.documentElement;
if (preferences.theme === 'dark' || (preferences.theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
}, [preferences.theme]);
return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-950 flex justify-center text-slate-900 dark:text-slate-100 font-sans transition-colors duration-300 overflow-x-hidden relative">
{/* Background Tech Elements */}
<div className="fixed inset-0 pointer-events-none z-0 overflow-hidden">
<div className="absolute top-0 left-0 w-full h-full bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-indigo-100/50 via-slate-100/20 to-transparent dark:from-indigo-900/20 dark:via-slate-900/40 dark:to-slate-950" />
<div className="absolute top-[-10%] right-[-10%] w-[500px] h-[500px] bg-purple-500/10 rounded-full blur-[100px] animate-pulse" />
<div className="absolute bottom-[-10%] left-[-10%] w-[500px] h-[500px] bg-cyan-500/10 rounded-full blur-[100px] animate-pulse" style={{ animationDelay: '2s' }} />
</div>
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className={clsx(
"w-full min-h-screen z-10 flex flex-col relative",
// Responsive layout: Mobile (centered max-w-md), Desktop (full width max-w-6xl)
"md:max-w-6xl md:px-8",
// Keep mobile behavior for mobile view
"md:w-full md:items-stretch md:bg-transparent md:shadow-none",
// Mobile specific
"max-w-md bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl md:backdrop-blur-none shadow-2xl md:bg-none",
className
)}
>
{children}
</motion.div>
</div>
);
};

51
src/index.css Normal file
View File

@@ -0,0 +1,51 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background-color: #f8fafc;
--text-color: #0f172a;
}
.dark {
--background-color: #020617;
--text-color: #f8fafc;
}
body {
background-color: var(--background-color);
color: var(--text-color);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@layer utilities {
.text-glow {
text-shadow: 0 0 10px rgba(99, 102, 241, 0.5);
}
.cursor-blink {
animation: blink 1s step-end infinite;
}
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
/* Custom scrollbar for desktop admin panel */
.custom-scrollbar::-webkit-scrollbar {
width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background-color: rgba(156, 163, 175, 0.5);
border-radius: 20px;
}
.dark .custom-scrollbar::-webkit-scrollbar-thumb {
background-color: rgba(75, 85, 99, 0.5);
}

14
src/main.tsx Normal file
View File

@@ -0,0 +1,14 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,350 @@
import React, { useState } from 'react';
import {
NavBar,
List,
SwipeAction,
Switch,
Button,
Modal,
Form,
Input,
TextArea,
Dialog,
Toast,
Tag,
FloatingBubble,
Image as AntImage
} from 'antd-mobile';
import { Plus, Eye, Trash2, Image as ImageIcon } from 'lucide-react';
import { useAppStore } from '../store/useAppStore';
import type { Template } from '../types';
import { generateCopy } from '../services/api';
import { Layout } from '../components/Layout';
import { useNavigate } from 'react-router-dom';
export const AdminDashboard: React.FC = () => {
const {
templates,
addTemplate,
updateTemplate,
deleteTemplate,
toggleTemplate,
logout,
posterUrls,
addPosterUrl,
removePosterUrl
} = useAppStore();
const [editingTemplate, setEditingTemplate] = useState<Template | null>(null);
const [isModalVisible, setIsModalVisible] = useState(false);
const [isPreviewVisible, setIsPreviewVisible] = useState(false);
const [previewName, setPreviewName] = useState('Test User');
const [previewResult, setPreviewResult] = useState('');
const [previewLoading, setPreviewLoading] = useState(false);
const [newPosterUrl, setNewPosterUrl] = useState('');
const navigate = useNavigate();
// Form instance
const [form] = Form.useForm();
const handleLogout = () => {
Dialog.confirm({
content: '确定要退出登录吗?',
onConfirm: () => {
logout();
navigate('/login');
},
});
};
const handleEdit = (template: Template) => {
setEditingTemplate(template);
form.setFieldsValue(template);
setIsModalVisible(true);
};
const handleAdd = () => {
setEditingTemplate(null);
form.resetFields();
setIsModalVisible(true);
};
const handleDelete = (id: string) => {
Dialog.confirm({
content: '确定要删除该模板吗?此操作不可恢复。',
confirmText: '删除',
cancelText: '取消',
onConfirm: () => {
deleteTemplate(id);
Toast.show({ content: '已删除', icon: 'success' });
},
});
};
const handleSave = async () => {
try {
const values = await form.validateFields();
if (editingTemplate) {
updateTemplate(editingTemplate.id, values);
Toast.show({ content: '更新成功', icon: 'success' });
} else {
addTemplate({ ...values, isEnabled: true });
Toast.show({ content: '添加成功', icon: 'success' });
}
setIsModalVisible(false);
} catch (error) {
console.error('Validation Failed:', error);
}
};
const handlePreview = async (template: Template) => {
setPreviewResult('');
setIsPreviewVisible(true);
setPreviewLoading(true);
try {
const systemPrompt = `You are a helpful assistant for generating WeChat Moments copy. Scenario: ${template.scenario}. Style: Casual, engaging. Use emojis.`;
const userPrompt = template.promptBody.replace('{{name}}', previewName);
const response = await generateCopy(template.modelName, [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
]);
setPreviewResult(response.choices?.[0]?.message?.content || 'Preview Failed');
} catch (error) {
setPreviewResult('Preview Failed: ' + (error as Error).message);
} finally {
setPreviewLoading(false);
}
};
const handleToggleTemplate = (id: string, currentStatus: boolean) => {
const enabledCount = templates.filter(t => t.isEnabled).length;
// Enabling a template
if (!currentStatus) {
// If we currently have 0, enabling 1 is fine (total 1).
// If we currently have 1, enabling 1 is fine (total 2).
// If we currently have 2, enabling 1 is fine (total 3).
// If we currently have 3, enabling 1 is fine (total 4).
// The rule says "Only 1 or 3".
// We'll warn if the RESULTING count is not 1 or 3.
const newCount = enabledCount + 1;
if (newCount !== 1 && newCount !== 3) {
Toast.show({ content: `注意:当前激活了 ${newCount} 个模板,建议保持 1 个或 3 个。`, icon: 'expressionless' });
}
} else {
// Disabling a template
const newCount = enabledCount - 1;
if (newCount !== 1 && newCount !== 3) {
if (newCount === 0) {
Toast.show({ content: '注意:至少需要激活 1 个模板。', icon: 'expressionless' });
} else {
Toast.show({ content: `注意:当前激活了 ${newCount} 个模板,建议保持 1 个或 3 个。`, icon: 'expressionless' });
}
}
}
toggleTemplate(id);
};
const handleAddPoster = () => {
if (!newPosterUrl.trim()) return;
if (posterUrls.length >= 9) {
Toast.show({ content: '最多只能添加 9 张海报', icon: 'fail' });
return;
}
addPosterUrl(newPosterUrl.trim());
setNewPosterUrl('');
Toast.show({ content: '添加成功', icon: 'success' });
};
const handleRemovePoster = (url: string) => {
Dialog.confirm({
content: '确定要删除这张海报吗?',
onConfirm: () => {
removePosterUrl(url);
Toast.show({ content: '已删除', icon: 'success' });
},
});
};
const rightActions = (template: Template) => [
{
key: 'edit',
text: '编辑',
color: 'primary',
onClick: () => handleEdit(template),
},
{
key: 'delete',
text: '删除',
color: 'danger',
onClick: () => handleDelete(template.id),
},
];
return (
<Layout className="bg-white/80 dark:bg-slate-900/80 md:bg-white/90 md:dark:bg-slate-900/90 backdrop-blur rounded-none md:rounded-3xl shadow-none md:shadow-2xl md:my-8 md:h-[calc(100vh-4rem)] md:overflow-hidden md:border border-white/20">
<div className="sticky top-0 z-50 bg-white/80 dark:bg-slate-900/80 backdrop-blur border-b border-slate-200 dark:border-slate-800">
<NavBar
back="退出"
onBack={handleLogout}
right={<Button size="mini" color="primary" onClick={handleAdd}><Plus size={16} /></Button>}
className="text-slate-800 dark:text-white"
>
</NavBar>
</div>
<div className="flex-1 overflow-y-auto p-2 md:p-6 custom-scrollbar space-y-6">
{/* Poster Management Section */}
<div className="bg-white/50 dark:bg-slate-800/50 rounded-xl p-4 border border-slate-100 dark:border-slate-800">
<h3 className="text-sm font-bold text-slate-500 dark:text-slate-400 mb-3 flex items-center gap-2">
<ImageIcon size={16} />
({posterUrls.length}/9)
</h3>
<div className="flex gap-2 mb-4">
<Input
placeholder="输入图片 URL..."
value={newPosterUrl}
onChange={setNewPosterUrl}
className="flex-1 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg px-2"
/>
<Button color="primary" size="small" onClick={handleAddPoster} disabled={!newPosterUrl.trim() || posterUrls.length >= 9}>
</Button>
</div>
<div className="grid grid-cols-3 gap-2">
{posterUrls.map((url, index) => (
<div key={index} className="relative group aspect-[3/4] rounded-lg overflow-hidden bg-slate-100 dark:bg-slate-900">
<AntImage src={url} fit="cover" className="w-full h-full" />
<div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
<Button
color="danger"
fill="none"
size="mini"
onClick={() => handleRemovePoster(url)}
className="bg-white/20 hover:bg-white/40 rounded-full p-1"
>
<Trash2 size={16} className="text-white" />
</Button>
</div>
</div>
))}
{posterUrls.length === 0 && (
<div className="col-span-3 text-center py-4 text-xs text-slate-400">
URL
</div>
)}
</div>
</div>
<List header="现有模板列表" className="bg-transparent">
{templates.map(template => (
<SwipeAction key={template.id} rightActions={rightActions(template)}>
<List.Item
className="bg-white/50 dark:bg-slate-800/50 hover:bg-white/80 dark:hover:bg-slate-800/80 transition-colors mb-2 rounded-xl overflow-hidden border border-slate-100 dark:border-slate-800"
prefix={
<div className="w-10 h-10 rounded-full bg-indigo-100 dark:bg-indigo-900/50 flex items-center justify-center text-indigo-600 dark:text-indigo-400 font-bold shadow-sm">
{template.title.charAt(0)}
</div>
}
description={
<div className="text-xs text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
{template.scenario}
</div>
}
extra={
<div className="flex items-center gap-2">
<Button
size="mini"
fill="none"
onClick={(e) => { e.stopPropagation(); handlePreview(template); }}
className="hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full w-8 h-8 p-0 flex items-center justify-center"
>
<Eye size={18} className="text-slate-500" />
</Button>
<Switch
checked={template.isEnabled}
onChange={() => handleToggleTemplate(template.id, template.isEnabled)}
style={{ '--checked-color': '#4f46e5' }}
/>
</div>
}
>
<div className="font-medium text-slate-800 dark:text-slate-200">{template.title}</div>
<Tag color="primary" fill="outline" className="mt-1 text-xs scale-90 origin-left border-indigo-200 text-indigo-600 bg-indigo-50 dark:bg-indigo-900/20 dark:border-indigo-800 dark:text-indigo-300">
{template.modelName}
</Tag>
</List.Item>
</SwipeAction>
))}
</List>
</div>
<FloatingBubble
axis="xy"
magnetic="x"
style={{ '--initial-position-bottom': '24px', '--initial-position-right': '24px', '--background': '#4f46e5' }}
onClick={handleAdd}
>
<Plus size={24} color="#fff" />
</FloatingBubble>
{/* Edit/Add Modal */}
<Modal
visible={isModalVisible}
title={editingTemplate ? '编辑模板' : '新增模板'}
content={
<Form form={form} layout="vertical">
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
<Input placeholder="例如:工作成就" />
</Form.Item>
<Form.Item name="scenario" label="适用场景" rules={[{ required: true }]}>
<Input placeholder="例如:分享项目上线喜悦" />
</Form.Item>
<Form.Item name="modelName" label="模型名称" rules={[{ required: true }]}>
<Input placeholder="qwen-plus / qwen-max / qwen3.5-plus" defaultValue="qwen3.5-plus" />
</Form.Item>
<Form.Item name="promptBody" label="Prompt (使用 {{name}} 占位)" rules={[{ required: true }]}>
<TextArea rows={4} placeholder="Prompt 内容..." />
</Form.Item>
</Form>
}
closeOnAction
onClose={() => setIsModalVisible(false)}
actions={[
{ key: 'cancel', text: '取消', onClick: () => setIsModalVisible(false) },
{ key: 'confirm', text: '保存', primary: true, onClick: handleSave, style: { color: '#4f46e5' } },
]}
/>
{/* Preview Modal */}
<Modal
visible={isPreviewVisible}
title="实时预览"
content={
<div className="space-y-4">
<Input
value={previewName}
onChange={setPreviewName}
placeholder="测试姓名"
className="border border-slate-200 dark:border-slate-700 p-2 rounded-lg bg-slate-50 dark:bg-slate-800"
/>
<div className="bg-slate-100 dark:bg-slate-800 p-3 rounded-lg min-h-[100px] text-sm whitespace-pre-wrap text-slate-700 dark:text-slate-300">
{previewLoading ? '生成中...' : previewResult || '点击预览查看效果'}
</div>
</div>
}
closeOnAction
onClose={() => setIsPreviewVisible(false)}
actions={[
{ key: 'close', text: '关闭', onClick: () => setIsPreviewVisible(false) },
]}
/>
</Layout>
);
};

76
src/pages/AdminLogin.tsx Normal file
View File

@@ -0,0 +1,76 @@
import React, { useState } from 'react';
import { Button, Input, Card, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { useAppStore } from '../store/useAppStore';
import { Layout } from '../components/Layout';
import { Lock, User } from 'lucide-react';
import { motion } from 'framer-motion';
export const AdminLogin: React.FC = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { login } = useAppStore();
const navigate = useNavigate();
const handleLogin = () => {
// Mock authentication
if (username === 'admin' && password === 'admin123') {
login(username);
Toast.show({ content: '登录成功', icon: 'success' });
navigate('/admin/dashboard');
} else {
Toast.show({ content: '用户名或密码错误', icon: 'fail' });
}
};
return (
<Layout className="justify-center items-center">
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="w-full max-w-sm"
>
<Card className="p-8 shadow-2xl rounded-3xl bg-white/80 dark:bg-slate-900/80 backdrop-blur border border-white/20 dark:border-white/5">
<h1 className="text-2xl font-bold text-center mb-8 text-slate-800 dark:text-white"></h1>
<div className="space-y-4">
<div className="relative group">
<User className="absolute left-3 top-3 text-slate-400 group-focus-within:text-indigo-500 transition-colors" size={20} />
<Input
placeholder="用户名"
value={username}
onChange={setUsername}
className="pl-10 py-2 border border-slate-200 dark:border-slate-700 rounded-xl w-full bg-slate-50 dark:bg-slate-950/50 dark:text-white focus-within:border-indigo-500 focus-within:ring-2 focus-within:ring-indigo-500/20 transition-all"
/>
</div>
<div className="relative group">
<Lock className="absolute left-3 top-3 text-slate-400 group-focus-within:text-indigo-500 transition-colors" size={20} />
<Input
placeholder="密码"
type="password"
value={password}
onChange={setPassword}
className="pl-10 py-2 border border-slate-200 dark:border-slate-700 rounded-xl w-full bg-slate-50 dark:bg-slate-950/50 dark:text-white focus-within:border-indigo-500 focus-within:ring-2 focus-within:ring-indigo-500/20 transition-all"
/>
</div>
<Button
block
color="primary"
size="large"
onClick={handleLogin}
className="mt-6 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 border-none shadow-lg shadow-indigo-500/20 active:scale-[0.98] transition-all font-bold"
>
</Button>
<div className="text-center mt-4">
<span className="text-xs text-slate-400">默认账号: admin / admin123</span>
</div>
</div>
</Card>
</motion.div>
</Layout>
);
};

320
src/pages/Home.tsx Normal file
View File

@@ -0,0 +1,320 @@
import React, { useState, useEffect, useRef } from 'react';
import { Button, Input, Card, Toast, ErrorBlock } from 'antd-mobile';
import { Copy, RefreshCw, Sparkles, Wand2, Quote, UserCircle2, Download } from 'lucide-react';
import { useAppStore } from '../store/useAppStore';
import { generateCopyStream } from '../services/api';
import { Header } from '../components/Header';
import { Layout } from '../components/Layout';
import { Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import html2canvas from 'html2canvas';
export const Home: React.FC = () => {
const { templates, preferences, setLastUsedName, posterUrls } = useAppStore();
const [name, setName] = useState(preferences.lastUsedName || '');
const [loading, setLoading] = useState(false);
const [result, setResult] = useState('');
const [error, setError] = useState('');
const [currentScenario, setCurrentScenario] = useState('');
const [currentPosterUrl, setCurrentPosterUrl] = useState('');
// Ref for auto-scrolling to bottom of result
const resultEndRef = useRef<HTMLDivElement>(null);
const posterRef = useRef<HTMLDivElement>(null);
const handleGenerate = async () => {
if (!name.trim()) {
Toast.show({ content: '请输入姓名', position: 'bottom' });
return;
}
setLastUsedName(name);
setLoading(true);
setError('');
setResult('');
// Randomly select a poster if available
if (posterUrls.length > 0) {
const randomPoster = posterUrls[Math.floor(Math.random() * posterUrls.length)];
setCurrentPosterUrl(randomPoster);
} else {
setCurrentPosterUrl('');
}
try {
// 1. Filter enabled templates
const enabledTemplates = templates.filter(t => t.isEnabled);
if (enabledTemplates.length === 0) {
throw new Error('暂无可用模板,请联系管理员。');
}
// 2. Pick a random template
const randomTemplate = enabledTemplates[Math.floor(Math.random() * enabledTemplates.length)];
setCurrentScenario(randomTemplate.title);
// 3. Construct Prompt
const systemPrompt = `You are a helpful assistant for generating WeChat Moments copy.
Scenario: ${randomTemplate.scenario}.
Style: Casual, engaging, authentic.
Use emojis.`;
const userPrompt = randomTemplate.promptBody.replace('{{name}}', name);
// 4. Call API with Stream
await generateCopyStream(
randomTemplate.modelName,
[
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
],
(chunk) => {
setResult((prev) => prev + chunk);
},
(err) => {
console.error(err);
setError(err.message || '生成失败,请检查网络或联系管理员');
setLoading(false);
},
() => {
setLoading(false);
}
);
} catch (err) {
console.error(err);
setError((err as Error).message || '生成失败,请检查网络或联系管理员');
setLoading(false);
}
};
const copyToClipboard = () => {
if (!result) return;
navigator.clipboard.writeText(result).then(() => {
Toast.show({ content: '已复制到剪贴板', icon: 'success' });
});
};
const handleSaveImage = async () => {
if (!posterRef.current || !result) return;
try {
const canvas = await html2canvas(posterRef.current, {
useCORS: true,
scale: 2,
backgroundColor: null // Transparent background if needed, but poster usually has bg
});
const link = document.createElement('a');
link.download = `wx-moments-${Date.now()}.png`;
link.href = canvas.toDataURL('image/png');
link.click();
Toast.show({ content: '海报已保存', icon: 'success' });
} catch (err) {
console.error('Save failed:', err);
Toast.show({ content: '保存失败,请重试', icon: 'fail' });
}
};
useEffect(() => {
if (resultEndRef.current) {
resultEndRef.current.scrollIntoView({ behavior: 'smooth' });
}
}, [result]);
return (
<Layout>
<Header />
<main className="flex-1 p-4 md:p-8 flex flex-col md:flex-row gap-6 md:gap-12 md:items-start md:justify-center max-w-7xl mx-auto w-full">
{/* Left Section: Input */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, ease: "easeOut" }}
className="w-full md:w-1/3 md:sticky md:top-24 flex flex-col gap-6"
>
<div className="bg-white/80 dark:bg-slate-900/80 backdrop-blur-md rounded-3xl p-6 md:p-8 shadow-xl border border-white/20 dark:border-white/5 relative overflow-hidden group">
{/* Tech Decoration */}
<div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/10 rounded-full blur-3xl -mr-16 -mt-16 transition-all group-hover:bg-indigo-500/20" />
<h2 className="text-xl md:text-2xl font-bold text-slate-800 dark:text-white mb-6 flex items-center gap-3">
<span className="p-2 rounded-lg bg-indigo-100 dark:bg-indigo-900/50 text-indigo-600 dark:text-indigo-400">
<Wand2 size={24} />
</span>
AI
</h2>
<div className="mb-6 space-y-2">
<label className="text-sm font-medium text-slate-500 dark:text-slate-400 ml-1">
/
</label>
<div className="relative group/input">
<UserCircle2 className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within/input:text-indigo-500 transition-colors" size={20} />
<Input
placeholder="请输入名字..."
value={name}
onChange={setName}
clearable
style={{
'--font-size': '16px',
'--color': 'var(--text-color)',
}}
className="bg-slate-50 dark:bg-slate-950/50 rounded-xl px-3 py-3 pl-10 border border-slate-200 dark:border-slate-700 focus-within:border-indigo-500 focus-within:ring-4 focus-within:ring-indigo-500/10 transition-all duration-300"
/>
</div>
</div>
<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}>
<Button
block
color="primary"
size="large"
onClick={handleGenerate}
loading={loading && !result} // Only show loading spinner if no result yet
disabled={loading}
className="rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 border-none font-bold shadow-lg shadow-indigo-500/20 active:scale-[0.98] transition-all h-12 text-lg relative overflow-hidden"
>
{loading ? 'AI 正在思考...' : '立即生成文案'}
</Button>
</motion.div>
<div className="mt-4 text-center">
<p className="text-xs text-slate-400 dark:text-slate-500">
DashScope ·
</p>
</div>
</div>
</motion.div>
{/* Right Section: Result */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1, duration: 0.5, ease: "easeOut" }}
className="w-full md:w-2/3 min-h-[400px]"
>
{error && (
<motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}>
<ErrorBlock
status="default"
title="生成出错了"
description={error}
className="bg-white/50 dark:bg-slate-900/50 backdrop-blur rounded-2xl p-4 border border-red-200 dark:border-red-900/30"
/>
</motion.div>
)}
{!result && !loading && !error && (
<div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-600 border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-3xl p-12 bg-white/30 dark:bg-slate-900/30">
<Sparkles size={48} className="mb-4 opacity-50" />
<p className="text-lg"> AI </p>
</div>
)}
<AnimatePresence mode="wait">
{(result || loading) && (
<motion.div
key="result-card"
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: -20 }}
transition={{ type: "spring", stiffness: 300, damping: 30 }}
className="relative"
>
{currentScenario && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="absolute -top-3 left-6 z-10"
>
<span className="bg-indigo-500 text-white text-xs font-bold px-3 py-1 rounded-full shadow-lg flex items-center gap-1">
<Sparkles size={12} />
{currentScenario}
</span>
</motion.div>
)}
<div ref={posterRef} className="relative rounded-3xl overflow-hidden shadow-2xl transition-all">
{/* Background Image Layer */}
{currentPosterUrl && (
<div className="absolute inset-0 z-0">
<img
src={currentPosterUrl}
alt="Poster Background"
className="w-full h-full object-cover"
crossOrigin="anonymous"
/>
<div className="absolute inset-0 bg-black/40 backdrop-blur-[2px]" /> {/* Overlay for readability */}
</div>
)}
<Card
className={`${currentPosterUrl ? 'bg-transparent border-0 text-white' : 'bg-white dark:bg-slate-900 border-0'} rounded-3xl overflow-hidden relative z-10`}
bodyClassName="p-0"
style={{ background: currentPosterUrl ? 'transparent' : undefined }}
>
<div className="p-6 md:p-10 min-h-[300px] flex flex-col">
<div className="flex-1 relative">
<Quote className={`absolute -top-2 -left-2 w-16 h-16 transform -scale-x-100 ${currentPosterUrl ? 'text-white/30' : 'text-indigo-100 dark:text-indigo-900/30'}`} />
<div className={`relative z-10 text-lg md:text-xl leading-relaxed font-medium whitespace-pre-wrap font-sans ${currentPosterUrl ? 'text-white drop-shadow-md' : 'text-slate-700 dark:text-slate-200'}`}>
{result}
{loading && (
<span className={`inline-block w-2 h-5 ml-1 animate-pulse align-middle ${currentPosterUrl ? 'bg-white' : 'bg-indigo-500'}`} />
)}
</div>
<div ref={resultEndRef} />
</div>
</div>
</Card>
</div>
{/* Actions Bar (Outside of Poster Ref) */}
<div className="mt-6 flex justify-end gap-3">
<Button
size="middle"
fill="none"
onClick={handleGenerate}
disabled={loading}
className="bg-white/50 dark:bg-slate-800/50 backdrop-blur text-slate-600 dark:text-slate-300 hover:bg-white/80 dark:hover:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700"
>
<RefreshCw size={18} className={`mr-2 ${loading ? 'animate-spin' : ''}`} />
{loading ? '生成中' : '换一个'}
</Button>
<Button
size="middle"
color="primary"
fill="solid"
onClick={copyToClipboard}
disabled={loading || !result}
className="rounded-xl px-6 bg-indigo-600 hover:bg-indigo-700 border-none shadow-md shadow-indigo-500/20 flex items-center active:scale-95 transition-transform"
>
<Copy size={18} className="mr-2" />
</Button>
{currentPosterUrl && result && !loading && (
<Button
size="middle"
color="success"
fill="solid"
onClick={handleSaveImage}
className="rounded-xl px-6 bg-emerald-500 hover:bg-emerald-600 border-none shadow-md shadow-emerald-500/20 flex items-center text-white active:scale-95 transition-transform"
>
<Download size={18} className="mr-2" />
</Button>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
</main>
<footer className="py-6 text-center text-xs text-slate-400 dark:text-slate-600">
<Link to="/admin" className="hover:text-indigo-500 transition-colors">Admin Login</Link>
</footer>
</Layout>
);
};

34
src/services/api.test.ts Normal file
View File

@@ -0,0 +1,34 @@
import { generateCopy, dashScopeApi } from './api';
jest.mock('axios', () => {
const mAxiosInstance = {
post: jest.fn(),
interceptors: {
request: { use: jest.fn() },
response: { use: jest.fn() },
},
};
return {
__esModule: true,
default: {
create: jest.fn(() => mAxiosInstance),
},
};
});
describe('API Service', () => {
it('should generate copy successfully', async () => {
const mockResponse = {
data: {
choices: [{ message: { content: 'Test Content' } }],
},
};
// Get the mocked instance
const mockedAxios = dashScopeApi as unknown as { post: jest.Mock };
mockedAxios.post.mockResolvedValue(mockResponse);
const result = await generateCopy('qwen-plus', [{ role: 'user', content: 'test' }]);
expect(result).toEqual(mockResponse.data);
expect(mockedAxios.post).toHaveBeenCalledWith('/chat/completions', expect.any(Object));
});
});

167
src/services/api.ts Normal file
View File

@@ -0,0 +1,167 @@
import axios, { AxiosError } from 'axios';
import type { InternalAxiosRequestConfig } from 'axios';
// DashScope API Configuration
const API_KEY = import.meta.env.VITE_API_KEY;
const DASHSCOPE_BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
if (!API_KEY) {
console.warn('DashScope API Key is missing in .env file!');
}
// Create Axios instance for DashScope
export const dashScopeApi = axios.create({
baseURL: DASHSCOPE_BASE_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
},
timeout: 60000, // 60s timeout for AI generation
});
// Retry configuration
const MAX_RETRIES = 3;
const INITIAL_RETRY_DELAY = 1000;
// Request Interceptor
dashScopeApi.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
// Ensure API Key is present
if (!config.headers.Authorization && API_KEY) {
config.headers.Authorization = `Bearer ${API_KEY}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Response Interceptor with Retry Logic
dashScopeApi.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const config = error.config as InternalAxiosRequestConfig & { _retryCount?: number };
// Handle 401/403 errors (Auth issues)
if (error.response?.status === 401 || error.response?.status === 403) {
console.error('Authentication Error:', error.response.data);
// In a real app, you might redirect to login or refresh token here.
// Since this is a direct API call with a static key, we just log it.
return Promise.reject(error);
}
// Retry logic for 429 (Rate Limit) or 5xx (Server Errors)
if (config && (error.response?.status === 429 || (error.response?.status || 0) >= 500)) {
config._retryCount = config._retryCount || 0;
if (config._retryCount < MAX_RETRIES) {
config._retryCount += 1;
const delay = INITIAL_RETRY_DELAY * Math.pow(2, config._retryCount - 1); // Exponential backoff
console.log(`Retrying request... Attempt ${config._retryCount} after ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
return dashScopeApi(config);
}
}
return Promise.reject(error);
}
);
/**
* Generate text using DashScope (OpenAI Compatible)
* @param model Model name (e.g., qwen-plus)
* @param messages Chat messages
*/
export const generateCopy = async (model: string, messages: { role: string; content: string }[]) => {
try {
const response = await dashScopeApi.post('/chat/completions', {
model,
messages,
// stream: true, // TODO: Implement streaming if needed
});
return response.data;
} catch (error) {
console.error('Failed to generate copy:', error);
throw error;
}
};
/**
* Generate text stream using DashScope (OpenAI Compatible)
* @param model Model name
* @param messages Chat messages
* @param onChunk Callback for each text chunk
* @param onError Callback for errors
* @param onFinish Callback when stream finishes
*/
export const generateCopyStream = async (
model: string,
messages: { role: string; content: string }[],
onChunk: (chunk: string) => void,
onError: (error: Error) => void,
onFinish: () => void
) => {
try {
const response = await fetch(`${DASHSCOPE_BASE_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model,
messages,
stream: true,
}),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `API Error: ${response.status}`);
}
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) {
throw new Error('Response body is not readable');
}
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine || trimmedLine === 'data: [DONE]') continue;
if (trimmedLine.startsWith('data: ')) {
try {
const jsonStr = trimmedLine.replace('data: ', '');
const json = JSON.parse(jsonStr);
const content = json.choices?.[0]?.delta?.content || '';
if (content) {
onChunk(content);
}
} catch (e) {
console.error('Error parsing stream chunk:', e);
}
}
}
}
onFinish();
} catch (error) {
console.error('Stream generation failed:', error);
onError(error as Error);
}
};

16
src/setupTests.ts Normal file
View File

@@ -0,0 +1,16 @@
import '@testing-library/jest-dom';
// Mock matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});

118
src/store/useAppStore.ts Normal file
View File

@@ -0,0 +1,118 @@
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { AppState, Template, UserPreferences } from '../types';
// Default templates for the app
const INITIAL_TEMPLATES: Template[] = [
{
id: '1',
title: 'Work Achievement',
scenario: 'Share work success or milestone',
promptBody: 'You are an AI assistant helping a user write a WeChat Moments post. The user wants to share a work achievement. Keep it professional but personal. Include relevant emojis. The user name is {{name}}.',
isEnabled: true,
modelName: 'qwen3.5-plus',
createdAt: Date.now(),
updatedAt: Date.now(),
},
{
id: '2',
title: 'Travel/Leisure',
scenario: 'Sharing travel photos or weekend vibes',
promptBody: 'Create a relaxed, fun WeChat Moments post for a travel or weekend trip. Use casual language and plenty of emojis. Focus on the scenery and good mood. The user is {{name}}.',
isEnabled: true,
modelName: 'qwen3.5-plus',
createdAt: Date.now(),
updatedAt: Date.now(),
},
];
export const useAppStore = create<AppState>()(
persist(
(set) => ({
// Initial State
templates: INITIAL_TEMPLATES,
posterUrls: [], // Initial empty poster URLs
preferences: {
theme: 'system',
lastUsedName: '',
},
admin: {
isAuthenticated: false,
user: null,
},
// User Actions
setTheme: (theme: UserPreferences['theme']) =>
set((state) => ({ preferences: { ...state.preferences, theme } })),
setLastUsedName: (name: string) =>
set((state) => ({ preferences: { ...state.preferences, lastUsedName: name } })),
// Admin Actions (Simulated Auth)
login: (username: string) =>
set(() => ({
admin: {
isAuthenticated: true,
user: { username, role: 'admin' }
}
})),
logout: () =>
set(() => ({
admin: {
isAuthenticated: false,
user: null
}
})),
// Template CRUD
addTemplate: (templateData) =>
set((state) => ({
templates: [
...state.templates,
{
id: crypto.randomUUID(),
...templateData,
createdAt: Date.now(),
updatedAt: Date.now(),
},
],
})),
updateTemplate: (id, updates) =>
set((state) => ({
templates: state.templates.map((t) =>
t.id === id ? { ...t, ...updates, updatedAt: Date.now() } : t
),
})),
deleteTemplate: (id) =>
set((state) => ({
templates: state.templates.filter((t) => t.id !== id),
})),
toggleTemplate: (id) =>
set((state) => ({
templates: state.templates.map((t) =>
t.id === id ? { ...t, isEnabled: !t.isEnabled } : t
),
})),
// Poster CRUD
addPosterUrl: (url) =>
set((state) => ({
posterUrls: [...state.posterUrls, url].slice(0, 9), // Max 9 posters
})),
removePosterUrl: (url) =>
set((state) => ({
posterUrls: state.posterUrls.filter((u) => u !== url),
})),
}),
{
name: 'wx-pyq-storage', // key in localStorage
storage: createJSONStorage(() => localStorage),
// Optional: Only persist specific parts if needed, currently persisting all
}
)
);

48
src/types/index.ts Normal file
View File

@@ -0,0 +1,48 @@
export interface Template {
id: string;
title: string;
scenario: string;
promptBody: string;
isEnabled: boolean;
modelName: string; // e.g., qwen-plus, qwen-max, qwen3.5-plus
createdAt: number;
updatedAt: number;
}
export interface UserPreferences {
theme: 'light' | 'dark' | 'system';
lastUsedName?: string;
}
export interface AdminState {
isAuthenticated: boolean;
user: {
username: string;
role: 'admin' | 'user';
} | null;
}
export interface AppState {
templates: Template[];
posterUrls: string[]; // Global poster URLs (1-9)
preferences: UserPreferences;
admin: AdminState;
// Actions
setTheme: (theme: UserPreferences['theme']) => void;
setLastUsedName: (name: string) => void;
// Admin Actions
login: (username: string) => void;
logout: () => void;
// Template CRUD
addTemplate: (template: Omit<Template, 'id' | 'createdAt' | 'updatedAt'>) => void;
updateTemplate: (id: string, updates: Partial<Template>) => void;
deleteTemplate: (id: string) => void;
toggleTemplate: (id: string) => void;
// Poster CRUD
addPosterUrl: (url: string) => void;
removePosterUrl: (url: string) => void;
}

16
tailwind.config.js Normal file
View File

@@ -0,0 +1,16 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
darkMode: 'class',
theme: {
extend: {
colors: {
// Define any custom colors here if needed
}
},
},
plugins: [],
}

28
tsconfig.app.json Normal file
View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

26
tsconfig.node.json Normal file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

10
tsconfig.test.json Normal file
View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"verbatimModuleSyntax": false,
"module": "ESNext",
"moduleResolution": "bundler",
"types": ["node", "jest", "vite/client"]
},
"include": ["src"]
}

7
vite.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})