commit
a35459e3dc
@ -0,0 +1,18 @@
|
|||||||
|
# 忽略整个文件夹(最常用)
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
|
||||||
|
# 忽略特定路径的文件夹
|
||||||
|
logs/
|
||||||
|
temp/
|
||||||
|
cache/
|
||||||
|
|
||||||
|
# 忽略所有名为 xxx 的文件夹(无论在哪一层)
|
||||||
|
**/node_modules/
|
||||||
|
|
||||||
|
# 忽略根目录下的文件夹(不加斜杠会匹配所有层级)
|
||||||
|
/node_modules/ # 仅忽略根目录的 node_modules
|
||||||
|
node_modules/ # 忽略所有层级的 node_modules
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
# ============================================
|
||||||
|
# A股智投分析平台 - 前端环境变量(测试环境)
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# API 配置
|
||||||
|
VITE_API_URL=http://localhost:3000/api/v1
|
||||||
|
VITE_WS_URL=ws://localhost:3000
|
||||||
|
|
||||||
|
# 应用信息
|
||||||
|
VITE_APP_NAME=A股智投分析平台
|
||||||
|
VITE_APP_VERSION=1.0.0
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
# API 配置
|
||||||
|
VITE_API_URL=http://localhost:3000/api/v1
|
||||||
|
VITE_WS_URL=ws://localhost:3000
|
||||||
|
|
||||||
|
# 其他配置
|
||||||
|
VITE_APP_NAME=A股智投分析平台
|
||||||
|
VITE_APP_VERSION=1.0.0
|
||||||
@ -0,0 +1,73 @@
|
|||||||
|
# React + TypeScript + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
|
|
||||||
|
## React Compiler
|
||||||
|
|
||||||
|
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
|
||||||
|
// Remove tseslint.configs.recommended and replace with this
|
||||||
|
tseslint.configs.recommendedTypeChecked,
|
||||||
|
// Alternatively, use this for stricter rules
|
||||||
|
tseslint.configs.strictTypeChecked,
|
||||||
|
// Optionally, add this for stylistic rules
|
||||||
|
tseslint.configs.stylisticTypeChecked,
|
||||||
|
|
||||||
|
// Other configs...
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// eslint.config.js
|
||||||
|
import reactX from 'eslint-plugin-react-x'
|
||||||
|
import reactDom from 'eslint-plugin-react-dom'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
// Enable lint rules for React
|
||||||
|
reactX.configs['recommended-typescript'],
|
||||||
|
// Enable lint rules for React DOM
|
||||||
|
reactDom.configs.recommended,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
# 服务器配置
|
||||||
|
PORT=3000
|
||||||
|
NODE_ENV=development
|
||||||
|
|
||||||
|
# 数据库配置
|
||||||
|
DATABASE_URL=mysql://user:password@localhost:3306/aguzhitou
|
||||||
|
|
||||||
|
# Redis配置
|
||||||
|
REDIS_URL=redis://localhost:6379
|
||||||
|
|
||||||
|
# JWT配置
|
||||||
|
JWT_SECRET=your-secret-key-min-32-characters-long
|
||||||
|
JWT_EXPIRES_IN=7d
|
||||||
|
|
||||||
|
# AKShare配置
|
||||||
|
AKSHARE_URL=http://localhost:8000
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
LOG_LEVEL=info
|
||||||
|
LOG_DIR=./logs
|
||||||
|
|
||||||
|
# 限流配置
|
||||||
|
RATE_LIMIT_WINDOW_MS=60000
|
||||||
|
RATE_LIMIT_MAX_REQUESTS=100
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
module.exports = {
|
||||||
|
parser: '@typescript-eslint/parser',
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 2022,
|
||||||
|
sourceType: 'module',
|
||||||
|
project: './tsconfig.json',
|
||||||
|
},
|
||||||
|
plugins: ['@typescript-eslint'],
|
||||||
|
extends: [
|
||||||
|
'eslint:recommended',
|
||||||
|
'plugin:@typescript-eslint/recommended',
|
||||||
|
],
|
||||||
|
root: true,
|
||||||
|
env: {
|
||||||
|
node: true,
|
||||||
|
es6: true,
|
||||||
|
},
|
||||||
|
ignorePatterns: ['.eslintrc.js', 'dist/', 'node_modules/'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/interface-name-prefix': 'off',
|
||||||
|
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||||
|
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||||
|
'@typescript-eslint/no-explicit-any': 'warn',
|
||||||
|
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
||||||
|
},
|
||||||
|
};
|
||||||
@ -0,0 +1,41 @@
|
|||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
|
||||||
|
# Environment variables
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Database
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
coverage/
|
||||||
|
|
||||||
|
# Misc
|
||||||
|
.cache/
|
||||||
|
temp/
|
||||||
|
tmp/
|
||||||
@ -0,0 +1,82 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
# 后端应用
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- PORT=3000
|
||||||
|
- DATABASE_URL=mysql://root:rootpass@mysql:3306/aguzhitou
|
||||||
|
- REDIS_URL=redis://redis:6379
|
||||||
|
- JWT_SECRET=${JWT_SECRET:-your-secret-key-min-32-characters-long}
|
||||||
|
- JWT_EXPIRES_IN=7d
|
||||||
|
- LOG_LEVEL=info
|
||||||
|
- AKSHARE_URL=http://akshare:8000
|
||||||
|
depends_on:
|
||||||
|
mysql:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
volumes:
|
||||||
|
- ./logs:/app/logs
|
||||||
|
restart: always
|
||||||
|
networks:
|
||||||
|
- aguzhitou-network
|
||||||
|
|
||||||
|
# MySQL 数据库
|
||||||
|
mysql:
|
||||||
|
image: mysql:8.0
|
||||||
|
environment:
|
||||||
|
- MYSQL_ROOT_PASSWORD=rootpass
|
||||||
|
- MYSQL_DATABASE=aguzhitou
|
||||||
|
- MYSQL_CHARSET=utf8mb4
|
||||||
|
- MYSQL_COLLATION=utf8mb4_unicode_ci
|
||||||
|
volumes:
|
||||||
|
- mysql_data:/var/lib/mysql
|
||||||
|
ports:
|
||||||
|
- "3306:3306"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-prootpass"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
restart: always
|
||||||
|
networks:
|
||||||
|
- aguzhitou-network
|
||||||
|
command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
|
||||||
|
|
||||||
|
# Redis 缓存
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
restart: always
|
||||||
|
networks:
|
||||||
|
- aguzhitou-network
|
||||||
|
|
||||||
|
# AKShare 数据服务(可选)
|
||||||
|
akshare:
|
||||||
|
image: registry.cn-shanghai.aliyuncs.com/akshare/akshare:latest
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
restart: always
|
||||||
|
networks:
|
||||||
|
- aguzhitou-network
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mysql_data:
|
||||||
|
redis_data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
aguzhitou-network:
|
||||||
|
driver: bridge
|
||||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"name": "aguzhitou-backend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "A股智投分析平台后端服务",
|
||||||
|
"main": "dist/app.js",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/app.ts",
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/app.js",
|
||||||
|
"db:generate": "prisma generate",
|
||||||
|
"db:migrate": "prisma migrate dev",
|
||||||
|
"db:deploy": "prisma migrate deploy",
|
||||||
|
"db:seed": "tsx prisma/seed.ts",
|
||||||
|
"db:studio": "prisma studio",
|
||||||
|
"lint": "eslint src --ext .ts",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/client": "^5.10.0",
|
||||||
|
"axios": "^1.6.7",
|
||||||
|
"bcryptjs": "^2.4.3",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.4.5",
|
||||||
|
"express": "^4.18.3",
|
||||||
|
"express-rate-limit": "^7.2.0",
|
||||||
|
"helmet": "^7.1.0",
|
||||||
|
"ioredis": "^5.3.2",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"node-cron": "^3.0.3",
|
||||||
|
"socket.io": "^4.7.4",
|
||||||
|
"winston": "^3.12.0",
|
||||||
|
"winston-daily-rotate-file": "^5.0.0",
|
||||||
|
"zod": "^3.22.4"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bcryptjs": "^2.4.6",
|
||||||
|
"@types/cors": "^2.8.17",
|
||||||
|
"@types/express": "^4.17.21",
|
||||||
|
"@types/jsonwebtoken": "^9.0.6",
|
||||||
|
"@types/node": "^20.11.24",
|
||||||
|
"@types/node-cron": "^3.0.11",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^7.1.1",
|
||||||
|
"@typescript-eslint/parser": "^7.1.1",
|
||||||
|
"eslint": "^8.57.0",
|
||||||
|
"prisma": "^5.10.0",
|
||||||
|
"tsx": "^4.7.1",
|
||||||
|
"typescript": "^5.3.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,205 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "mysql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 市场指数
|
||||||
|
model MarketIndex {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @unique
|
||||||
|
code String @unique
|
||||||
|
current Float
|
||||||
|
change Float
|
||||||
|
changePercent Float
|
||||||
|
volume BigInt
|
||||||
|
turnover BigInt
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([code])
|
||||||
|
@@map("market_indices")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 版块信息
|
||||||
|
model Sector {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
name String @unique
|
||||||
|
code String @unique
|
||||||
|
stocks Stock[]
|
||||||
|
quotes SectorQuote[]
|
||||||
|
klines SectorKLine[]
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([code])
|
||||||
|
@@map("sectors")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 版块行情
|
||||||
|
model SectorQuote {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sectorCode String @map("sector_code")
|
||||||
|
sector Sector @relation(fields: [sectorCode], references: [code])
|
||||||
|
current Float
|
||||||
|
change Float
|
||||||
|
changePercent Float
|
||||||
|
volume BigInt
|
||||||
|
turnover BigInt
|
||||||
|
momentumScore Float @default(50)
|
||||||
|
rank Int @default(0)
|
||||||
|
previousRank Int @default(0) @map("previous_rank")
|
||||||
|
quoteTime DateTime @map("quote_time")
|
||||||
|
|
||||||
|
@@index([sectorCode])
|
||||||
|
@@index([quoteTime])
|
||||||
|
@@map("sector_quotes")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 版块K线数据
|
||||||
|
model SectorKLine {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sectorCode String @map("sector_code")
|
||||||
|
sector Sector @relation(fields: [sectorCode], references: [code])
|
||||||
|
period String // day/week/month
|
||||||
|
date DateTime
|
||||||
|
open Float
|
||||||
|
high Float
|
||||||
|
low Float
|
||||||
|
close Float
|
||||||
|
volume BigInt
|
||||||
|
|
||||||
|
@@unique([sectorCode, period, date])
|
||||||
|
@@index([sectorCode])
|
||||||
|
@@index([date])
|
||||||
|
@@map("sector_klines")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 股票信息
|
||||||
|
model Stock {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
code String @unique
|
||||||
|
name String
|
||||||
|
sectorCode String? @map("sector_code")
|
||||||
|
sector Sector? @relation(fields: [sectorCode], references: [code])
|
||||||
|
marketCap BigInt? @map("market_cap")
|
||||||
|
pe Float?
|
||||||
|
pb Float?
|
||||||
|
quotes StockQuote[]
|
||||||
|
klines StockKLine[]
|
||||||
|
favorites UserFavorite[]
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([code])
|
||||||
|
@@index([sectorCode])
|
||||||
|
@@map("stocks")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 股票行情
|
||||||
|
model StockQuote {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
stockCode String @map("stock_code")
|
||||||
|
stock Stock @relation(fields: [stockCode], references: [code])
|
||||||
|
price Float
|
||||||
|
open Float
|
||||||
|
high Float
|
||||||
|
low Float
|
||||||
|
preClose Float @map("pre_close")
|
||||||
|
volume BigInt
|
||||||
|
turnover BigInt
|
||||||
|
changePercent Float @map("change_percent")
|
||||||
|
turnoverRate Float? @map("turnover_rate")
|
||||||
|
amplitude Float?
|
||||||
|
quoteTime DateTime @map("quote_time")
|
||||||
|
|
||||||
|
@@index([stockCode])
|
||||||
|
@@index([quoteTime])
|
||||||
|
@@map("stock_quotes")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 股票K线数据
|
||||||
|
model StockKLine {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
stockCode String @map("stock_code")
|
||||||
|
stock Stock @relation(fields: [stockCode], references: [code])
|
||||||
|
period String // day/week/month
|
||||||
|
date DateTime
|
||||||
|
open Float
|
||||||
|
high Float
|
||||||
|
low Float
|
||||||
|
close Float
|
||||||
|
volume BigInt
|
||||||
|
ma5 Float?
|
||||||
|
ma10 Float?
|
||||||
|
ma20 Float?
|
||||||
|
ma30 Float?
|
||||||
|
ma60 Float?
|
||||||
|
|
||||||
|
@@unique([stockCode, period, date])
|
||||||
|
@@index([stockCode])
|
||||||
|
@@index([date])
|
||||||
|
@@map("stock_klines")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用户
|
||||||
|
model User {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
username String @unique
|
||||||
|
email String @unique
|
||||||
|
password String
|
||||||
|
favorites UserFavorite[]
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("users")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用户自选股
|
||||||
|
model UserFavorite {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
userId String @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
stockCode String @map("stock_code")
|
||||||
|
stock Stock @relation(fields: [stockCode], references: [code])
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
@@unique([userId, stockCode])
|
||||||
|
@@index([userId])
|
||||||
|
@@map("user_favorites")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 新高新低股票记录
|
||||||
|
model HighLowStock {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
stockCode String @map("stock_code")
|
||||||
|
type String // high/low
|
||||||
|
price Float
|
||||||
|
date DateTime
|
||||||
|
daysToHighLow Int @map("days_to_highlow")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
@@index([stockCode])
|
||||||
|
@@index([type])
|
||||||
|
@@index([date])
|
||||||
|
@@map("high_low_stocks")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 动量股票推荐
|
||||||
|
model MomentumStock {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
stockCode String @map("stock_code")
|
||||||
|
momentumScore Float @map("momentum_score")
|
||||||
|
tags String? // JSON array
|
||||||
|
volumeRatio Float @map("volume_ratio")
|
||||||
|
breakThrough Boolean @default(false) @map("break_through")
|
||||||
|
date DateTime
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
@@index([stockCode])
|
||||||
|
@@index([date])
|
||||||
|
@@map("momentum_stocks")
|
||||||
|
}
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('Start seeding...');
|
||||||
|
|
||||||
|
// 创建版块数据
|
||||||
|
const sectors = [
|
||||||
|
{ name: '半导体', code: '880491' },
|
||||||
|
{ name: '新能源', code: '880952' },
|
||||||
|
{ name: '医药生物', code: '880122' },
|
||||||
|
{ name: '白酒', code: '880381' },
|
||||||
|
{ name: '银行', code: '880471' },
|
||||||
|
{ name: '证券', code: '880472' },
|
||||||
|
{ name: '保险', code: '880473' },
|
||||||
|
{ name: '房地产', code: '880482' },
|
||||||
|
{ name: '汽车', code: '880391' },
|
||||||
|
{ name: '电子', code: '880494' },
|
||||||
|
{ name: '计算机', code: '880952' },
|
||||||
|
{ name: '通信', code: '880495' },
|
||||||
|
{ name: '传媒', code: '880952' },
|
||||||
|
{ name: '军工', code: '880954' },
|
||||||
|
{ name: '有色金属', code: '880324' },
|
||||||
|
{ name: '钢铁', code: '880318' },
|
||||||
|
{ name: '煤炭', code: '880952' },
|
||||||
|
{ name: '化工', code: '880336' },
|
||||||
|
{ name: '建筑材料', code: '880344' },
|
||||||
|
{ name: '机械设备', code: '880952' },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const sector of sectors) {
|
||||||
|
await prisma.sector.upsert({
|
||||||
|
where: { code: sector.code },
|
||||||
|
update: {},
|
||||||
|
create: sector,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log(`Created ${sectors.length} sectors`);
|
||||||
|
|
||||||
|
// 创建市场指数
|
||||||
|
const indices = [
|
||||||
|
{ name: '上证指数', code: '000001', current: 3050.32, change: 15.23, changePercent: 0.5, volume: BigInt(450000000), turnover: BigInt(4200000000), sortOrder: 1 },
|
||||||
|
{ name: '深证成指', code: '399001', current: 9850.15, change: -25.6, changePercent: -0.26, volume: BigInt(520000000), turnover: BigInt(5100000000), sortOrder: 2 },
|
||||||
|
{ name: '创业板指', code: '399006', current: 1950.45, change: 8.75, changePercent: 0.45, volume: BigInt(180000000), turnover: BigInt(2100000000), sortOrder: 3 },
|
||||||
|
{ name: '科创50', code: '000688', current: 850.32, change: -5.23, changePercent: -0.61, volume: BigInt(65000000), turnover: BigInt(950000000), sortOrder: 4 },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const index of indices) {
|
||||||
|
await prisma.marketIndex.upsert({
|
||||||
|
where: { code: index.code },
|
||||||
|
update: {},
|
||||||
|
create: index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log(`Created ${indices.length} market indices`);
|
||||||
|
|
||||||
|
// 创建示例股票数据
|
||||||
|
const stocks = [
|
||||||
|
{ code: '000001', name: '平安银行', sectorCode: '880471' },
|
||||||
|
{ code: '000002', name: '万科A', sectorCode: '880482' },
|
||||||
|
{ code: '000063', name: '中兴通讯', sectorCode: '880495' },
|
||||||
|
{ code: '000100', name: 'TCL科技', sectorCode: '880494' },
|
||||||
|
{ code: '000333', name: '美的集团', sectorCode: '880952' },
|
||||||
|
{ code: '000568', name: '泸州老窖', sectorCode: '880381' },
|
||||||
|
{ code: '000651', name: '格力电器', sectorCode: '880952' },
|
||||||
|
{ code: '000725', name: '京东方A', sectorCode: '880494' },
|
||||||
|
{ code: '000768', name: '中航西飞', sectorCode: '880954' },
|
||||||
|
{ code: '000858', name: '五粮液', sectorCode: '880381' },
|
||||||
|
{ code: '600000', name: '浦发银行', sectorCode: '880471' },
|
||||||
|
{ code: '600009', name: '上海机场', sectorCode: '880952' },
|
||||||
|
{ code: '600016', name: '民生银行', sectorCode: '880471' },
|
||||||
|
{ code: '600028', name: '中国石化', sectorCode: '880952' },
|
||||||
|
{ code: '600030', name: '中信证券', sectorCode: '880472' },
|
||||||
|
{ code: '600031', name: '三一重工', sectorCode: '880952' },
|
||||||
|
{ code: '600036', name: '招商银行', sectorCode: '880471' },
|
||||||
|
{ code: '600048', name: '保利发展', sectorCode: '880482' },
|
||||||
|
{ code: '600050', name: '中国联通', sectorCode: '880495' },
|
||||||
|
{ code: '600104', name: '上汽集团', sectorCode: '880391' },
|
||||||
|
{ code: '600196', name: '复星医药', sectorCode: '880122' },
|
||||||
|
{ code: '600276', name: '恒瑞医药', sectorCode: '880122' },
|
||||||
|
{ code: '600309', name: '万华化学', sectorCode: '880336' },
|
||||||
|
{ code: '600519', name: '贵州茅台', sectorCode: '880381' },
|
||||||
|
{ code: '600900', name: '长江电力', sectorCode: '880952' },
|
||||||
|
{ code: '601012', name: '隆基绿能', sectorCode: '880952' },
|
||||||
|
{ code: '601088', name: '中国神华', sectorCode: '880952' },
|
||||||
|
{ code: '601166', name: '兴业银行', sectorCode: '880471' },
|
||||||
|
{ code: '601288', name: '农业银行', sectorCode: '880471' },
|
||||||
|
{ code: '601318', name: '中国平安', sectorCode: '880473' },
|
||||||
|
{ code: '601398', name: '工商银行', sectorCode: '880471' },
|
||||||
|
{ code: '601888', name: '中国中免', sectorCode: '880952' },
|
||||||
|
{ code: '603288', name: '海天味业', sectorCode: '880952' },
|
||||||
|
{ code: '688981', name: '中芯国际', sectorCode: '880491' },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const stock of stocks) {
|
||||||
|
await prisma.stock.upsert({
|
||||||
|
where: { code: stock.code },
|
||||||
|
update: {},
|
||||||
|
create: {
|
||||||
|
...stock,
|
||||||
|
marketCap: BigInt(Math.floor(Math.random() * 1000000000000) + 10000000000),
|
||||||
|
pe: Number((Math.random() * 50 + 5).toFixed(2)),
|
||||||
|
pb: Number((Math.random() * 10 + 0.5).toFixed(2)),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log(`Created ${stocks.length} stocks`);
|
||||||
|
|
||||||
|
console.log('Seeding finished');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@ -0,0 +1,139 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import helmet from 'helmet';
|
||||||
|
import { createServer } from 'http';
|
||||||
|
import config from './config';
|
||||||
|
import { connectDatabase } from './config/database';
|
||||||
|
import redis from './config/redis';
|
||||||
|
import routes from './routes';
|
||||||
|
import { errorHandler, notFoundHandler } from './middleware/errorHandler';
|
||||||
|
import { requestLogger } from './middleware/logger';
|
||||||
|
import { generalLimiter } from './middleware/rateLimiter';
|
||||||
|
import StockSocket from './websocket/stockSocket';
|
||||||
|
import { marketDataSyncJob } from './jobs/syncMarketData';
|
||||||
|
import { dataSyncService } from './services/dataSyncService';
|
||||||
|
import logger from './utils/logger';
|
||||||
|
|
||||||
|
// 创建 Express 应用
|
||||||
|
const app = express();
|
||||||
|
const server = createServer(app);
|
||||||
|
|
||||||
|
// WebSocket 服务
|
||||||
|
let stockSocket: StockSocket | null = null;
|
||||||
|
|
||||||
|
// 中间件
|
||||||
|
app.use(helmet({
|
||||||
|
contentSecurityPolicy: false, // 开发环境禁用CSP
|
||||||
|
}));
|
||||||
|
app.use(cors({
|
||||||
|
origin: '*',
|
||||||
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||||
|
allowedHeaders: ['Content-Type', 'Authorization'],
|
||||||
|
}));
|
||||||
|
app.use(express.json({ limit: '10mb' }));
|
||||||
|
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
|
||||||
|
|
||||||
|
// 请求日志
|
||||||
|
app.use(requestLogger);
|
||||||
|
|
||||||
|
// 限流
|
||||||
|
app.use(generalLimiter);
|
||||||
|
|
||||||
|
// API 路由
|
||||||
|
app.use('/api/v1', routes);
|
||||||
|
|
||||||
|
// 错误处理
|
||||||
|
app.use(notFoundHandler);
|
||||||
|
app.use(errorHandler);
|
||||||
|
|
||||||
|
// 启动服务器
|
||||||
|
async function startServer(): Promise<void> {
|
||||||
|
try {
|
||||||
|
// 连接数据库
|
||||||
|
await connectDatabase();
|
||||||
|
logger.info('Database connected');
|
||||||
|
|
||||||
|
// 测试 Redis 连接(可选,连接失败不影响启动)
|
||||||
|
try {
|
||||||
|
await redis.ping();
|
||||||
|
logger.info('Redis connected');
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('Redis not available, using memory cache fallback');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化基础数据
|
||||||
|
await dataSyncService.initBaseData();
|
||||||
|
|
||||||
|
// 启动 WebSocket 服务
|
||||||
|
stockSocket = new StockSocket(server);
|
||||||
|
logger.info('WebSocket server started');
|
||||||
|
|
||||||
|
// 启动定时任务
|
||||||
|
marketDataSyncJob.start();
|
||||||
|
|
||||||
|
// 启动 HTTP 服务器
|
||||||
|
server.listen(config.port, () => {
|
||||||
|
logger.info(`Server is running on port ${config.port}`);
|
||||||
|
logger.info(`Environment: ${config.nodeEnv}`);
|
||||||
|
logger.info(`API URL: http://localhost:${config.port}/api/v1`);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to start server:', error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 优雅关闭
|
||||||
|
async function gracefulShutdown(): Promise<void> {
|
||||||
|
logger.info('Shutting down server...');
|
||||||
|
|
||||||
|
// 停止定时任务
|
||||||
|
marketDataSyncJob.stop();
|
||||||
|
|
||||||
|
// 关闭 WebSocket
|
||||||
|
if (stockSocket) {
|
||||||
|
// 通知所有客户端
|
||||||
|
// stockSocket.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭 HTTP 服务器
|
||||||
|
server.close(() => {
|
||||||
|
logger.info('HTTP server closed');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关闭 Redis 连接(如果已连接)
|
||||||
|
try {
|
||||||
|
await redis.quit();
|
||||||
|
logger.info('Redis connection closed');
|
||||||
|
} catch (error) {
|
||||||
|
// Redis 未连接,忽略错误
|
||||||
|
}
|
||||||
|
|
||||||
|
// 断开数据库连接
|
||||||
|
const { disconnectDatabase } = await import('./config/database');
|
||||||
|
await disconnectDatabase();
|
||||||
|
logger.info('Database connection closed');
|
||||||
|
|
||||||
|
logger.info('Server shutdown complete');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 进程信号处理
|
||||||
|
process.on('SIGTERM', gracefulShutdown);
|
||||||
|
process.on('SIGINT', gracefulShutdown);
|
||||||
|
|
||||||
|
// 未捕获的异常
|
||||||
|
process.on('uncaughtException', (error) => {
|
||||||
|
logger.error('Uncaught Exception:', error);
|
||||||
|
gracefulShutdown();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 未处理的 Promise 拒绝
|
||||||
|
process.on('unhandledRejection', (reason, promise) => {
|
||||||
|
logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 启动服务
|
||||||
|
startServer();
|
||||||
|
|
||||||
|
export default app;
|
||||||
@ -0,0 +1,52 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
// Prisma 客户端实例
|
||||||
|
const prisma = new PrismaClient({
|
||||||
|
log: [
|
||||||
|
{ emit: 'event', level: 'query' },
|
||||||
|
{ emit: 'event', level: 'error' },
|
||||||
|
{ emit: 'event', level: 'info' },
|
||||||
|
{ emit: 'event', level: 'warn' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 查询日志
|
||||||
|
prisma.$on('query', (e: any) => {
|
||||||
|
logger.debug('Prisma Query', {
|
||||||
|
query: e.query,
|
||||||
|
params: e.params,
|
||||||
|
duration: `${e.duration}ms`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 错误日志
|
||||||
|
prisma.$on('error', (e: any) => {
|
||||||
|
logger.error('Prisma Error', {
|
||||||
|
message: e.message,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 连接数据库
|
||||||
|
export async function connectDatabase(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await prisma.$connect();
|
||||||
|
logger.info('Database connected successfully');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Database connection failed:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 断开数据库连接
|
||||||
|
export async function disconnectDatabase(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
logger.info('Database disconnected');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Database disconnect error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default prisma;
|
||||||
@ -0,0 +1,51 @@
|
|||||||
|
import dotenv from 'dotenv';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
dotenv.config({ path: path.resolve(__dirname, '../../.env') });
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
// 服务器配置
|
||||||
|
port: parseInt(process.env.PORT || '3000', 10),
|
||||||
|
nodeEnv: process.env.NODE_ENV || 'development',
|
||||||
|
|
||||||
|
// 数据库配置
|
||||||
|
databaseUrl: process.env.DATABASE_URL || 'mysql://root:root@localhost:3306/aguzhitou',
|
||||||
|
|
||||||
|
// Redis配置
|
||||||
|
redisUrl: process.env.REDIS_URL || 'redis://localhost:6379',
|
||||||
|
|
||||||
|
// JWT配置
|
||||||
|
jwtSecret: process.env.JWT_SECRET || 'default-secret-key',
|
||||||
|
jwtExpiresIn: process.env.JWT_EXPIRES_IN || '7d',
|
||||||
|
|
||||||
|
// AKShare配置
|
||||||
|
akshareUrl: process.env.AKSHARE_URL || 'http://localhost:8000',
|
||||||
|
|
||||||
|
// 日志配置
|
||||||
|
logLevel: process.env.LOG_LEVEL || 'info',
|
||||||
|
logDir: process.env.LOG_DIR || './logs',
|
||||||
|
|
||||||
|
// 限流配置
|
||||||
|
rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '60000', 10),
|
||||||
|
rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS || '100', 10),
|
||||||
|
|
||||||
|
// 缓存过期时间(秒)
|
||||||
|
cacheTtl: {
|
||||||
|
marketIndices: 60,
|
||||||
|
upDownStats: 60,
|
||||||
|
priceDistribution: 60,
|
||||||
|
sectors: 60,
|
||||||
|
sectorDetail: 300,
|
||||||
|
stockDetail: 60,
|
||||||
|
klineData: 300,
|
||||||
|
searchResults: 300,
|
||||||
|
},
|
||||||
|
|
||||||
|
// 交易时间配置
|
||||||
|
tradingHours: {
|
||||||
|
morning: { start: '09:30', end: '11:30' },
|
||||||
|
afternoon: { start: '13:00', end: '15:00' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
@ -0,0 +1,45 @@
|
|||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { marketService } from '../services/marketService';
|
||||||
|
import { asyncHandler } from '../middleware/errorHandler';
|
||||||
|
import { ApiResponse } from '../types';
|
||||||
|
|
||||||
|
export const marketController = {
|
||||||
|
// 获取市场指数
|
||||||
|
getMarketIndices: asyncHandler(async (_req: Request, res: Response) => {
|
||||||
|
const indices = await marketService.getMarketIndices();
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: indices,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取涨跌家数统计
|
||||||
|
getUpDownStats: asyncHandler(async (_req: Request, res: Response) => {
|
||||||
|
const stats = await marketService.getUpDownStats();
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: stats,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取涨跌幅分布
|
||||||
|
getPriceDistribution: asyncHandler(async (_req: Request, res: Response) => {
|
||||||
|
const distribution = await marketService.getPriceDistribution();
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: distribution,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
};
|
||||||
@ -0,0 +1,131 @@
|
|||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { sectorService } from '../services/sectorService';
|
||||||
|
import { asyncHandler, NotFoundError } from '../middleware/errorHandler';
|
||||||
|
import { ApiResponse } from '../types';
|
||||||
|
|
||||||
|
export const sectorController = {
|
||||||
|
// 获取版块列表
|
||||||
|
getSectors: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { sort, order } = req.query;
|
||||||
|
|
||||||
|
let sectors = await sectorService.getSectorsWithMomentum();
|
||||||
|
|
||||||
|
// 排序处理
|
||||||
|
if (sort) {
|
||||||
|
const sortField = sort as string;
|
||||||
|
const sortOrder = order === 'asc' ? 1 : -1;
|
||||||
|
|
||||||
|
sectors.sort((a, b) => {
|
||||||
|
const aVal = a[sortField as keyof typeof a] || 0;
|
||||||
|
const bVal = b[sortField as keyof typeof b] || 0;
|
||||||
|
return (aVal > bVal ? 1 : -1) * sortOrder;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: sectors,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取版块详情
|
||||||
|
getSectorDetail: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { sector_code } = req.params;
|
||||||
|
|
||||||
|
const sector = await sectorService.getSectorDetail(sector_code);
|
||||||
|
|
||||||
|
if (!sector) {
|
||||||
|
throw new NotFoundError('版块不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: sector,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取版块历史排名
|
||||||
|
getSectorRankHistory: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { sector_code } = req.params;
|
||||||
|
const days = parseInt(req.query.days as string) || 30;
|
||||||
|
|
||||||
|
const history = await sectorService.getSectorRankHistory(sector_code, days);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: history,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取版块内股票
|
||||||
|
getSectorStocks: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { sector_code } = req.params;
|
||||||
|
const { sort, limit } = req.query;
|
||||||
|
|
||||||
|
let stocks = await sectorService.getSectorStocks(
|
||||||
|
sector_code,
|
||||||
|
parseInt(limit as string) || 20
|
||||||
|
);
|
||||||
|
|
||||||
|
// 排序处理
|
||||||
|
if (sort) {
|
||||||
|
const sortField = sort as string;
|
||||||
|
stocks.sort((a, b) => {
|
||||||
|
const aVal = a[sortField as keyof typeof a] || 0;
|
||||||
|
const bVal = b[sortField as keyof typeof b] || 0;
|
||||||
|
return bVal > aVal ? 1 : -1;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: stocks,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取版块内动量股票
|
||||||
|
getSectorMomentumStocks: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { sector_code } = req.params;
|
||||||
|
|
||||||
|
const stocks = await sectorService.getSectorMomentumStocks(sector_code);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: stocks,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取版块K线数据
|
||||||
|
getSectorKLine: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { sector_code } = req.params;
|
||||||
|
const period = (req.query.period as string) || 'day';
|
||||||
|
const days = parseInt(req.query.days as string) || 60;
|
||||||
|
|
||||||
|
// 这里需要从服务获取K线数据
|
||||||
|
// 暂时返回空数组
|
||||||
|
const klines: any[] = [];
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: klines,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
};
|
||||||
@ -0,0 +1,123 @@
|
|||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { stockService } from '../services/stockService';
|
||||||
|
import { asyncHandler, NotFoundError, BadRequestError } from '../middleware/errorHandler';
|
||||||
|
import { ApiResponse } from '../types';
|
||||||
|
import { searchKeywordSchema, periodSchema } from '../utils/validator';
|
||||||
|
|
||||||
|
export const stockController = {
|
||||||
|
// 搜索股票
|
||||||
|
search: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { keyword, type } = req.query;
|
||||||
|
|
||||||
|
if (!keyword || typeof keyword !== 'string') {
|
||||||
|
throw new BadRequestError('搜索关键词不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const validatedKeyword = searchKeywordSchema.parse(keyword);
|
||||||
|
|
||||||
|
let sectors: any[] = [];
|
||||||
|
let stocks: any[] = [];
|
||||||
|
|
||||||
|
if (!type || type === 'all' || type === 'sector') {
|
||||||
|
sectors = await stockService.searchSectors(validatedKeyword);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!type || type === 'all' || type === 'stock') {
|
||||||
|
stocks = await stockService.searchStocks(validatedKeyword);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: {
|
||||||
|
sectors,
|
||||||
|
stocks,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取股票详情
|
||||||
|
getStockDetail: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { stock_code } = req.params;
|
||||||
|
|
||||||
|
const stock = await stockService.getStockDetail(stock_code);
|
||||||
|
|
||||||
|
if (!stock) {
|
||||||
|
throw new NotFoundError('股票不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: stock,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取股票K线数据
|
||||||
|
getStockKLine: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { stock_code } = req.params;
|
||||||
|
const period = periodSchema.parse(req.query.period || 'day');
|
||||||
|
const days = parseInt(req.query.days as string) || 60;
|
||||||
|
|
||||||
|
const klines = await stockService.getKLineData(stock_code, period, days);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: klines,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取新高股票
|
||||||
|
getNewHighStocks: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const days = parseInt(req.query.days as string) || 20;
|
||||||
|
const limit = parseInt(req.query.limit as string) || 20;
|
||||||
|
|
||||||
|
const stocks = await stockService.getNewHighStocks(days, limit);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: stocks,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取新低股票
|
||||||
|
getNewLowStocks: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const days = parseInt(req.query.days as string) || 20;
|
||||||
|
const limit = parseInt(req.query.limit as string) || 20;
|
||||||
|
|
||||||
|
const stocks = await stockService.getNewLowStocks(days, limit);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: stocks,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取动量股推荐
|
||||||
|
getMomentumRecommendation: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const limit = parseInt(req.query.limit as string) || 15;
|
||||||
|
|
||||||
|
const stocks = await stockService.getMomentumStocks(limit);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: stocks,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
};
|
||||||
@ -0,0 +1,253 @@
|
|||||||
|
import { Request, Response } from 'express';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import prisma from '../config/database';
|
||||||
|
import { generateToken } from '../middleware/auth';
|
||||||
|
import { asyncHandler, BadRequestError, UnauthorizedError, NotFoundError } from '../middleware/errorHandler';
|
||||||
|
import { ApiResponse, User } from '../types';
|
||||||
|
import { userRegisterSchema, userLoginSchema, favoriteStockSchema } from '../utils/validator';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export const userController = {
|
||||||
|
// 用户注册
|
||||||
|
register: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const data = userRegisterSchema.parse(req.body);
|
||||||
|
|
||||||
|
// 检查用户是否已存在
|
||||||
|
const existingUser = await prisma.user.findFirst({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ email: data.email },
|
||||||
|
{ username: data.username },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existingUser) {
|
||||||
|
throw new BadRequestError('用户名或邮箱已存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加密密码
|
||||||
|
const hashedPassword = await bcrypt.hash(data.password, 10);
|
||||||
|
|
||||||
|
// 创建用户
|
||||||
|
const user = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
username: data.username,
|
||||||
|
email: data.email,
|
||||||
|
password: hashedPassword,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 生成 token
|
||||||
|
const token = generateToken({
|
||||||
|
userId: user.id,
|
||||||
|
username: user.username,
|
||||||
|
email: user.email,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`User registered: ${user.username}`);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: '注册成功',
|
||||||
|
data: {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
email: user.email,
|
||||||
|
token,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 用户登录
|
||||||
|
login: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const data = userLoginSchema.parse(req.body);
|
||||||
|
|
||||||
|
// 查找用户
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { email: data.email },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedError('邮箱或密码错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证密码
|
||||||
|
const isValid = await bcrypt.compare(data.password, user.password);
|
||||||
|
|
||||||
|
if (!isValid) {
|
||||||
|
throw new UnauthorizedError('邮箱或密码错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成 token
|
||||||
|
const token = generateToken({
|
||||||
|
userId: user.id,
|
||||||
|
username: user.username,
|
||||||
|
email: user.email,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`User logged in: ${user.username}`);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: '登录成功',
|
||||||
|
data: {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
email: user.email,
|
||||||
|
token,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取用户信息
|
||||||
|
getProfile: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const userId = req.user!.id;
|
||||||
|
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
email: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new NotFoundError('用户不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: user,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 获取自选股
|
||||||
|
getFavorites: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const userId = req.user!.id;
|
||||||
|
|
||||||
|
const favorites = await prisma.userFavorite.findMany({
|
||||||
|
where: { userId },
|
||||||
|
include: {
|
||||||
|
stock: {
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
sector: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = favorites.map((f) => ({
|
||||||
|
code: f.stock.code,
|
||||||
|
name: f.stock.name,
|
||||||
|
price: f.stock.quotes[0]?.price || 0,
|
||||||
|
changePercent: f.stock.quotes[0]?.changePercent || 0,
|
||||||
|
industry: f.stock.sector?.name,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 添加自选股
|
||||||
|
addFavorite: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const userId = req.user!.id;
|
||||||
|
const { stockCode } = favoriteStockSchema.parse(req.body);
|
||||||
|
|
||||||
|
// 检查股票是否存在
|
||||||
|
const stock = await prisma.stock.findUnique({
|
||||||
|
where: { code: stockCode },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!stock) {
|
||||||
|
throw new NotFoundError('股票不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否已添加
|
||||||
|
const existing = await prisma.userFavorite.findUnique({
|
||||||
|
where: {
|
||||||
|
userId_stockCode: {
|
||||||
|
userId,
|
||||||
|
stockCode,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
throw new BadRequestError('该股票已在自选股中');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.userFavorite.create({
|
||||||
|
data: {
|
||||||
|
userId,
|
||||||
|
stockCode,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`User ${req.user!.username} added favorite: ${stockCode}`);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: '添加成功',
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 删除自选股
|
||||||
|
removeFavorite: asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const userId = req.user!.id;
|
||||||
|
const { stock_code } = req.params;
|
||||||
|
|
||||||
|
const favorite = await prisma.userFavorite.findUnique({
|
||||||
|
where: {
|
||||||
|
userId_stockCode: {
|
||||||
|
userId,
|
||||||
|
stockCode: stock_code,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!favorite) {
|
||||||
|
throw new NotFoundError('自选股不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.userFavorite.delete({
|
||||||
|
where: {
|
||||||
|
userId_stockCode: {
|
||||||
|
userId,
|
||||||
|
stockCode: stock_code,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`User ${req.user!.username} removed favorite: ${stock_code}`);
|
||||||
|
|
||||||
|
const response: ApiResponse = {
|
||||||
|
code: 200,
|
||||||
|
message: '删除成功',
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json(response);
|
||||||
|
}),
|
||||||
|
};
|
||||||
@ -0,0 +1,132 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
import config from '../config';
|
||||||
|
import { UnauthorizedError } from './errorHandler';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
// 扩展 Express Request 类型
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request {
|
||||||
|
user?: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// JWT Payload 类型
|
||||||
|
interface JWTPayload {
|
||||||
|
userId: string;
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
iat: number;
|
||||||
|
exp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证 JWT Token
|
||||||
|
export function verifyToken(token: string): JWTPayload {
|
||||||
|
return jwt.verify(token, config.jwtSecret) as JWTPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成 JWT Token
|
||||||
|
export function generateToken(payload: { userId: string; username: string; email: string }): string {
|
||||||
|
return jwt.sign(payload, config.jwtSecret, {
|
||||||
|
expiresIn: config.jwtExpiresIn,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 认证中间件
|
||||||
|
export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||||
|
try {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
|
||||||
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||||
|
throw new UnauthorizedError('缺少认证令牌');
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = authHeader.substring(7);
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedError('无效的认证令牌');
|
||||||
|
}
|
||||||
|
|
||||||
|
const decoded = verifyToken(token);
|
||||||
|
|
||||||
|
req.user = {
|
||||||
|
id: decoded.userId,
|
||||||
|
username: decoded.username,
|
||||||
|
email: decoded.email,
|
||||||
|
};
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof jwt.TokenExpiredError) {
|
||||||
|
next(new UnauthorizedError('认证令牌已过期'));
|
||||||
|
} else if (error instanceof jwt.JsonWebTokenError) {
|
||||||
|
next(new UnauthorizedError('无效的认证令牌'));
|
||||||
|
} else {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 可选认证中间件(不强制要求登录)
|
||||||
|
export function optionalAuthMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||||
|
try {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
|
||||||
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = authHeader.substring(7);
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const decoded = verifyToken(token);
|
||||||
|
|
||||||
|
req.user = {
|
||||||
|
id: decoded.userId,
|
||||||
|
username: decoded.username,
|
||||||
|
email: decoded.email,
|
||||||
|
};
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
// 可选认证失败不抛出错误
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 管理员权限检查中间件
|
||||||
|
export function adminMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||||
|
if (!req.user) {
|
||||||
|
next(new UnauthorizedError('请先登录'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 这里可以添加管理员权限检查逻辑
|
||||||
|
// 例如从数据库查询用户角色
|
||||||
|
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录用户操作日志
|
||||||
|
export function logUserAction(action: string) {
|
||||||
|
return (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
if (req.user) {
|
||||||
|
logger.info(`User Action: ${action}`, {
|
||||||
|
userId: req.user.id,
|
||||||
|
username: req.user.username,
|
||||||
|
url: req.url,
|
||||||
|
method: req.method,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -0,0 +1,141 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import { ZodError } from 'zod';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
// 自定义错误类
|
||||||
|
export class AppError extends Error {
|
||||||
|
public statusCode: number;
|
||||||
|
public isOperational: boolean;
|
||||||
|
|
||||||
|
constructor(message: string, statusCode: number, isOperational = true) {
|
||||||
|
super(message);
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
this.isOperational = isOperational;
|
||||||
|
Error.captureStackTrace(this, this.constructor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 404 错误
|
||||||
|
export class NotFoundError extends AppError {
|
||||||
|
constructor(message: string = '资源不存在') {
|
||||||
|
super(message, 404);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 400 错误
|
||||||
|
export class BadRequestError extends AppError {
|
||||||
|
constructor(message: string = '请求参数错误') {
|
||||||
|
super(message, 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 401 错误
|
||||||
|
export class UnauthorizedError extends AppError {
|
||||||
|
constructor(message: string = '未授权,请先登录') {
|
||||||
|
super(message, 401);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 403 错误
|
||||||
|
export class ForbiddenError extends AppError {
|
||||||
|
constructor(message: string = '禁止访问') {
|
||||||
|
super(message, 403);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 429 错误
|
||||||
|
export class TooManyRequestsError extends AppError {
|
||||||
|
constructor(message: string = '请求过于频繁,请稍后再试') {
|
||||||
|
super(message, 429);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 错误响应格式
|
||||||
|
interface ErrorResponse {
|
||||||
|
code: number;
|
||||||
|
message: string;
|
||||||
|
stack?: string;
|
||||||
|
errors?: any[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 全局错误处理中间件
|
||||||
|
export function errorHandler(
|
||||||
|
err: Error | AppError | ZodError,
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
_next: NextFunction
|
||||||
|
): void {
|
||||||
|
let statusCode = 500;
|
||||||
|
let message = '服务器内部错误';
|
||||||
|
let errors: any[] | undefined;
|
||||||
|
|
||||||
|
// 处理 Zod 验证错误
|
||||||
|
if (err instanceof ZodError) {
|
||||||
|
statusCode = 400;
|
||||||
|
message = '请求参数验证失败';
|
||||||
|
errors = err.errors.map((e) => ({
|
||||||
|
path: e.path.join('.'),
|
||||||
|
message: e.message,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
// 处理自定义应用错误
|
||||||
|
else if (err instanceof AppError) {
|
||||||
|
statusCode = err.statusCode;
|
||||||
|
message = err.message;
|
||||||
|
}
|
||||||
|
// 处理其他错误
|
||||||
|
else {
|
||||||
|
message = err.message || message;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录错误日志
|
||||||
|
if (statusCode >= 500) {
|
||||||
|
logger.error('Server Error:', {
|
||||||
|
error: err.message,
|
||||||
|
stack: err.stack,
|
||||||
|
url: req.url,
|
||||||
|
method: req.method,
|
||||||
|
ip: req.ip,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
logger.warn('Client Error:', {
|
||||||
|
statusCode,
|
||||||
|
message,
|
||||||
|
url: req.url,
|
||||||
|
method: req.method,
|
||||||
|
ip: req.ip,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const response: ErrorResponse = {
|
||||||
|
code: statusCode,
|
||||||
|
message,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 开发环境显示堆栈
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
response.stack = err.stack;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示验证错误详情
|
||||||
|
if (errors) {
|
||||||
|
response.errors = errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 未找到路由处理
|
||||||
|
export function notFoundHandler(req: Request, res: Response): void {
|
||||||
|
res.status(404).json({
|
||||||
|
code: 404,
|
||||||
|
message: `未找到路由: ${req.method} ${req.url}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 异步路由处理包装器
|
||||||
|
export function asyncHandler(fn: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
|
||||||
|
return (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
Promise.resolve(fn(req, res, next)).catch(next);
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -0,0 +1,51 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
// 请求日志中间件
|
||||||
|
export function requestLogger(req: Request, res: Response, next: NextFunction): void {
|
||||||
|
const start = Date.now();
|
||||||
|
|
||||||
|
res.on('finish', () => {
|
||||||
|
const duration = Date.now() - start;
|
||||||
|
const logData = {
|
||||||
|
method: req.method,
|
||||||
|
url: req.url,
|
||||||
|
status: res.statusCode,
|
||||||
|
duration: `${duration}ms`,
|
||||||
|
ip: req.ip,
|
||||||
|
userAgent: req.get('user-agent'),
|
||||||
|
userId: req.user?.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (res.statusCode >= 400) {
|
||||||
|
logger.warn('HTTP Request', logData);
|
||||||
|
} else {
|
||||||
|
logger.info('HTTP Request', logData);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 慢请求警告中间件
|
||||||
|
export function slowRequestLogger(threshold: number = 1000) {
|
||||||
|
return (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const start = Date.now();
|
||||||
|
|
||||||
|
res.on('finish', () => {
|
||||||
|
const duration = Date.now() - start;
|
||||||
|
|
||||||
|
if (duration > threshold) {
|
||||||
|
logger.warn('Slow Request', {
|
||||||
|
method: req.method,
|
||||||
|
url: req.url,
|
||||||
|
duration: `${duration}ms`,
|
||||||
|
threshold: `${threshold}ms`,
|
||||||
|
ip: req.ip,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -0,0 +1,33 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import marketRoutes from './marketRoutes';
|
||||||
|
import sectorRoutes from './sectorRoutes';
|
||||||
|
import stockRoutes from './stockRoutes';
|
||||||
|
import userRoutes from './userRoutes';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// 市场数据路由
|
||||||
|
router.use('/market', marketRoutes);
|
||||||
|
|
||||||
|
// 版块数据路由
|
||||||
|
router.use('/sectors', sectorRoutes);
|
||||||
|
|
||||||
|
// 股票数据路由
|
||||||
|
router.use('/stocks', stockRoutes);
|
||||||
|
|
||||||
|
// 用户路由
|
||||||
|
router.use('/users', userRoutes);
|
||||||
|
|
||||||
|
// 健康检查
|
||||||
|
router.get('/health', (_req, res) => {
|
||||||
|
res.json({
|
||||||
|
code: 200,
|
||||||
|
message: 'success',
|
||||||
|
data: {
|
||||||
|
status: 'healthy',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import { marketController } from '../controllers/marketController';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// 获取市场指数
|
||||||
|
router.get('/indices', marketController.getMarketIndices);
|
||||||
|
|
||||||
|
// 获取涨跌家数统计
|
||||||
|
router.get('/updown-stats', marketController.getUpDownStats);
|
||||||
|
|
||||||
|
// 获取涨跌幅分布
|
||||||
|
router.get('/price-distribution', marketController.getPriceDistribution);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import { sectorController } from '../controllers/sectorController';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// 获取版块列表
|
||||||
|
router.get('/', sectorController.getSectors);
|
||||||
|
|
||||||
|
// 获取版块详情
|
||||||
|
router.get('/:sector_code', sectorController.getSectorDetail);
|
||||||
|
|
||||||
|
// 获取版块历史排名
|
||||||
|
router.get('/:sector_code/rank-history', sectorController.getSectorRankHistory);
|
||||||
|
|
||||||
|
// 获取版块内股票
|
||||||
|
router.get('/:sector_code/stocks', sectorController.getSectorStocks);
|
||||||
|
|
||||||
|
// 获取版块内动量股票
|
||||||
|
router.get('/:sector_code/momentum-stocks', sectorController.getSectorMomentumStocks);
|
||||||
|
|
||||||
|
// 获取版块K线数据
|
||||||
|
router.get('/:sector_code/kline', sectorController.getSectorKLine);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import { stockController } from '../controllers/stockController';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// 搜索股票
|
||||||
|
router.get('/search', stockController.search);
|
||||||
|
|
||||||
|
// 获取新高股票
|
||||||
|
router.get('/new-high', stockController.getNewHighStocks);
|
||||||
|
|
||||||
|
// 获取新低股票
|
||||||
|
router.get('/new-low', stockController.getNewLowStocks);
|
||||||
|
|
||||||
|
// 获取动量股推荐
|
||||||
|
router.get('/momentum-recommendation', stockController.getMomentumRecommendation);
|
||||||
|
|
||||||
|
// 获取股票详情
|
||||||
|
router.get('/:stock_code', stockController.getStockDetail);
|
||||||
|
|
||||||
|
// 获取股票K线数据
|
||||||
|
router.get('/:stock_code/kline', stockController.getStockKLine);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import { userController } from '../controllers/userController';
|
||||||
|
import { authMiddleware } from '../middleware/auth';
|
||||||
|
import { loginLimiter } from '../middleware/rateLimiter';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// 用户注册
|
||||||
|
router.post('/register', userController.register);
|
||||||
|
|
||||||
|
// 用户登录(限流)
|
||||||
|
router.post('/login', loginLimiter, userController.login);
|
||||||
|
|
||||||
|
// 获取用户信息(需要认证)
|
||||||
|
router.get('/profile', authMiddleware, userController.getProfile);
|
||||||
|
|
||||||
|
// 获取自选股(需要认证)
|
||||||
|
router.get('/favorites', authMiddleware, userController.getFavorites);
|
||||||
|
|
||||||
|
// 添加自选股(需要认证)
|
||||||
|
router.post('/favorites', authMiddleware, userController.addFavorite);
|
||||||
|
|
||||||
|
// 删除自选股(需要认证)
|
||||||
|
router.delete('/favorites/:stock_code', authMiddleware, userController.removeFavorite);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@ -0,0 +1,354 @@
|
|||||||
|
import axios from 'axios';
|
||||||
|
import prisma from '../config/database';
|
||||||
|
import { cache } from '../config/redis';
|
||||||
|
import config from '../config';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
import { AKShareStockSpot, AKShareKLine } from '../types';
|
||||||
|
|
||||||
|
export class DataSyncService {
|
||||||
|
private akshareBaseUrl: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.akshareBaseUrl = config.akshareUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 同步实时行情
|
||||||
|
async syncRealTimeQuotes(): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.info('Starting real-time quotes sync...');
|
||||||
|
|
||||||
|
// 从AKShare获取实时行情
|
||||||
|
const response = await axios.get(`${this.akshareBaseUrl}/stock_zh_a_spot`, {
|
||||||
|
timeout: 30000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const quotes: AKShareStockSpot[] = response.data;
|
||||||
|
|
||||||
|
if (!Array.isArray(quotes) || quotes.length === 0) {
|
||||||
|
logger.warn('No quotes data received from AKShare');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
let successCount = 0;
|
||||||
|
let failCount = 0;
|
||||||
|
|
||||||
|
// 批量处理
|
||||||
|
const batchSize = 100;
|
||||||
|
for (let i = 0; i < quotes.length; i += batchSize) {
|
||||||
|
const batch = quotes.slice(i, i + batchSize);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await prisma.$transaction(
|
||||||
|
batch.map((quote) =>
|
||||||
|
prisma.stockQuote.create({
|
||||||
|
data: {
|
||||||
|
stockCode: quote.code,
|
||||||
|
price: quote.price,
|
||||||
|
open: quote.open,
|
||||||
|
high: quote.high,
|
||||||
|
low: quote.low,
|
||||||
|
preClose: quote.pre_close,
|
||||||
|
volume: BigInt(quote.volume),
|
||||||
|
turnover: BigInt(quote.turnover),
|
||||||
|
changePercent: quote.change_percent,
|
||||||
|
quoteTime: now,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
successCount += batch.length;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to sync batch ${i / batchSize + 1}:`, error);
|
||||||
|
failCount += batch.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`Real-time quotes sync completed: ${successCount} success, ${failCount} failed`);
|
||||||
|
|
||||||
|
// 清除相关缓存
|
||||||
|
await cache.delPattern('market:*');
|
||||||
|
await cache.delPattern('sectors:*');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to sync real-time quotes:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 同步个股K线数据
|
||||||
|
async syncKLineData(stockCode: string, period: string = 'day'): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.info(`Syncing K-line data for ${stockCode}...`);
|
||||||
|
|
||||||
|
const endDate = new Date().toISOString().split('T')[0].replace(/-/g, '');
|
||||||
|
const startDate = this.getStartDate(period);
|
||||||
|
|
||||||
|
const response = await axios.get(`${this.akshareBaseUrl}/stock_zh_a_hist`, {
|
||||||
|
params: {
|
||||||
|
symbol: stockCode,
|
||||||
|
period: period === 'day' ? 'daily' : period === 'week' ? 'weekly' : 'monthly',
|
||||||
|
start_date: startDate,
|
||||||
|
end_date: endDate,
|
||||||
|
},
|
||||||
|
timeout: 30000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const klines: AKShareKLine[] = response.data;
|
||||||
|
|
||||||
|
if (!Array.isArray(klines) || klines.length === 0) {
|
||||||
|
logger.warn(`No K-line data received for ${stockCode}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用 upsert 批量插入或更新
|
||||||
|
for (const k of klines) {
|
||||||
|
await prisma.stockKLine.upsert({
|
||||||
|
where: {
|
||||||
|
stockCode_period_date: {
|
||||||
|
stockCode: stockCode,
|
||||||
|
period: period,
|
||||||
|
date: new Date(k.date),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
open: k.open,
|
||||||
|
high: k.high,
|
||||||
|
low: k.low,
|
||||||
|
close: k.close,
|
||||||
|
volume: BigInt(k.volume),
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
stockCode: stockCode,
|
||||||
|
period: period,
|
||||||
|
date: new Date(k.date),
|
||||||
|
open: k.open,
|
||||||
|
high: k.high,
|
||||||
|
low: k.low,
|
||||||
|
close: k.close,
|
||||||
|
volume: BigInt(k.volume),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`Synced ${klines.length} K-line records for ${stockCode}`);
|
||||||
|
|
||||||
|
// 清除缓存
|
||||||
|
await cache.delPattern(`stock:${stockCode}:kline:${period}:*`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to sync K-line data for ${stockCode}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取起始日期
|
||||||
|
private getStartDate(period: string): string {
|
||||||
|
const now = new Date();
|
||||||
|
let months = 6;
|
||||||
|
|
||||||
|
switch (period) {
|
||||||
|
case 'day':
|
||||||
|
months = 12;
|
||||||
|
break;
|
||||||
|
case 'week':
|
||||||
|
months = 24;
|
||||||
|
break;
|
||||||
|
case 'month':
|
||||||
|
months = 60;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
now.setMonth(now.getMonth() - months);
|
||||||
|
return now.toISOString().split('T')[0].replace(/-/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 同步版块行情
|
||||||
|
async syncSectorQuotes(): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.info('Starting sector quotes sync...');
|
||||||
|
|
||||||
|
// 获取所有版块
|
||||||
|
const sectors = await prisma.sector.findMany();
|
||||||
|
|
||||||
|
// 模拟版块数据(实际应该从数据源获取)
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
for (const sector of sectors) {
|
||||||
|
try {
|
||||||
|
// 这里应该从AKShare或其他数据源获取版块数据
|
||||||
|
// 暂时使用模拟数据
|
||||||
|
const changePercent = Math.random() * 10 - 5;
|
||||||
|
|
||||||
|
await prisma.sectorQuote.create({
|
||||||
|
data: {
|
||||||
|
sectorCode: sector.code,
|
||||||
|
current: 1000 + Math.random() * 500,
|
||||||
|
change: changePercent * 10,
|
||||||
|
changePercent: changePercent,
|
||||||
|
volume: BigInt(Math.floor(Math.random() * 100000000)),
|
||||||
|
turnover: BigInt(Math.floor(Math.random() * 1000000000)),
|
||||||
|
momentumScore: Math.random() * 60 + 30,
|
||||||
|
quoteTime: now,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to sync sector quote for ${sector.code}:`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`Sector quotes sync completed for ${sectors.length} sectors`);
|
||||||
|
|
||||||
|
// 清除缓存
|
||||||
|
await cache.delPattern('sectors:*');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to sync sector quotes:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 同步市场指数
|
||||||
|
async syncMarketIndices(): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.info('Starting market indices sync...');
|
||||||
|
|
||||||
|
// 从AKShare获取指数数据
|
||||||
|
const indices = [
|
||||||
|
{ name: '上证指数', code: '000001' },
|
||||||
|
{ name: '深证成指', code: '399001' },
|
||||||
|
{ name: '创业板指', code: '399006' },
|
||||||
|
{ name: '科创50', code: '000688' },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const index of indices) {
|
||||||
|
try {
|
||||||
|
// 这里应该从AKShare获取实际数据
|
||||||
|
// 暂时使用模拟数据
|
||||||
|
await prisma.marketIndex.upsert({
|
||||||
|
where: { code: index.code },
|
||||||
|
update: {
|
||||||
|
current: 3000 + Math.random() * 500,
|
||||||
|
change: Math.random() * 50 - 25,
|
||||||
|
changePercent: Math.random() * 2 - 1,
|
||||||
|
volume: BigInt(Math.floor(Math.random() * 500000000)),
|
||||||
|
turnover: BigInt(Math.floor(Math.random() * 5000000000)),
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
name: index.name,
|
||||||
|
code: index.code,
|
||||||
|
current: 3000 + Math.random() * 500,
|
||||||
|
change: Math.random() * 50 - 25,
|
||||||
|
changePercent: Math.random() * 2 - 1,
|
||||||
|
volume: BigInt(Math.floor(Math.random() * 500000000)),
|
||||||
|
turnover: BigInt(Math.floor(Math.random() * 5000000000)),
|
||||||
|
sortOrder: indices.indexOf(index),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to sync market index ${index.code}:`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('Market indices sync completed');
|
||||||
|
|
||||||
|
// 清除缓存
|
||||||
|
await cache.del('market:indices');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to sync market indices:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量同步所有股票K线数据
|
||||||
|
async syncAllStocksKLine(period: string = 'day'): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.info(`Starting batch K-line sync for period: ${period}...`);
|
||||||
|
|
||||||
|
const stocks = await prisma.stock.findMany({
|
||||||
|
select: { code: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
let successCount = 0;
|
||||||
|
let failCount = 0;
|
||||||
|
|
||||||
|
for (const stock of stocks) {
|
||||||
|
try {
|
||||||
|
await this.syncKLineData(stock.code, period);
|
||||||
|
successCount++;
|
||||||
|
|
||||||
|
// 添加延迟避免请求过快
|
||||||
|
await this.delay(100);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to sync K-line for ${stock.code}:`, error);
|
||||||
|
failCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`Batch K-line sync completed: ${successCount} success, ${failCount} failed`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to batch sync K-line data:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 延迟辅助函数
|
||||||
|
private delay(ms: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化基础数据
|
||||||
|
async initBaseData(): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.info('Initializing base data...');
|
||||||
|
|
||||||
|
// 检查是否已有数据
|
||||||
|
const sectorCount = await prisma.sector.count();
|
||||||
|
|
||||||
|
if (sectorCount === 0) {
|
||||||
|
// 初始化版块数据
|
||||||
|
const sectors = [
|
||||||
|
{ name: '半导体', code: '880491' },
|
||||||
|
{ name: '新能源', code: '880952' },
|
||||||
|
{ name: '医药生物', code: '880122' },
|
||||||
|
{ name: '白酒', code: '880952' },
|
||||||
|
{ name: '银行', code: '880471' },
|
||||||
|
{ name: '证券', code: '880472' },
|
||||||
|
{ name: '保险', code: '880473' },
|
||||||
|
{ name: '房地产', code: '880482' },
|
||||||
|
{ name: '汽车', code: '880391' },
|
||||||
|
{ name: '电子', code: '880494' },
|
||||||
|
{ name: '计算机', wire: '880952' },
|
||||||
|
{ name: '通信', code: '880495' },
|
||||||
|
{ name: '传媒', code: '880952' },
|
||||||
|
{ name: '军工', code: '880954' },
|
||||||
|
{ name: '有色金属', code: '880324' },
|
||||||
|
{ name: '钢铁', code: '880318' },
|
||||||
|
{ name: '煤炭', code: '880952' },
|
||||||
|
{ name: '化工', code: '880336' },
|
||||||
|
{ name: '建筑材料', code: '880344' },
|
||||||
|
{ name: '机械设备', code: '880952' },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const sector of sectors) {
|
||||||
|
try {
|
||||||
|
await prisma.sector.create({
|
||||||
|
data: sector as any,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to create sector ${sector.name}:`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`Created ${sectors.length} sectors`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化市场指数
|
||||||
|
await this.syncMarketIndices();
|
||||||
|
|
||||||
|
logger.info('Base data initialization completed');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to initialize base data:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const dataSyncService = new DataSyncService();
|
||||||
@ -0,0 +1,176 @@
|
|||||||
|
import prisma from '../config/database';
|
||||||
|
import { cache } from '../config/redis';
|
||||||
|
import config from '../config';
|
||||||
|
import { MarketIndex, PriceDistribution } from '../types';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class MarketService {
|
||||||
|
// 获取市场指数
|
||||||
|
async getMarketIndices(): Promise<MarketIndex[]> {
|
||||||
|
const cacheKey = 'market:indices';
|
||||||
|
const cached = await cache.get<MarketIndex[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const indices = await prisma.marketIndex.findMany({
|
||||||
|
orderBy: { sortOrder: 'asc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const result: MarketIndex[] = indices.map((index) => ({
|
||||||
|
name: index.name,
|
||||||
|
code: index.code,
|
||||||
|
current: index.current,
|
||||||
|
change: index.change,
|
||||||
|
changePercent: index.changePercent,
|
||||||
|
volume: Number(index.volume),
|
||||||
|
turnover: Number(index.turnover),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.marketIndices);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get market indices:', error);
|
||||||
|
// 返回默认数据
|
||||||
|
return this.getDefaultMarketIndices();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取默认市场指数数据
|
||||||
|
private getDefaultMarketIndices(): MarketIndex[] {
|
||||||
|
return [
|
||||||
|
{ name: '上证指数', code: '000001', current: 3050.32, change: 15.23, changePercent: 0.5, volume: 450000000, turnover: 4200000000 },
|
||||||
|
{ name: '深证成指', code: '399001', current: 9850.15, change: -25.6, changePercent: -0.26, volume: 520000000, turnover: 5100000000 },
|
||||||
|
{ name: '创业板指', code: '399006', current: 1950.45, change: 8.75, changePercent: 0.45, volume: 180000000, turnover: 2100000000 },
|
||||||
|
{ name: '科创50', code: '000688', current: 850.32, change: -5.23, changePercent: -0.61, volume: 65000000, turnover: 950000000 },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取涨跌家数统计
|
||||||
|
async getUpDownStats(): Promise<{ up: number; down: number; flat: number }> {
|
||||||
|
const cacheKey = 'market:updown:stats';
|
||||||
|
const cached = await cache.get<{ up: number; down: number; flat: number }>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
|
||||||
|
|
||||||
|
const stats = await prisma.stockQuote.groupBy({
|
||||||
|
by: ['stockCode'],
|
||||||
|
_max: {
|
||||||
|
quoteTime: true,
|
||||||
|
},
|
||||||
|
where: {
|
||||||
|
quoteTime: {
|
||||||
|
gte: fiveMinutesAgo,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取最新的行情数据
|
||||||
|
const latestQuotes = await Promise.all(
|
||||||
|
stats.map((s) =>
|
||||||
|
prisma.stockQuote.findFirst({
|
||||||
|
where: {
|
||||||
|
stockCode: s._max.quoteTime,
|
||||||
|
},
|
||||||
|
orderBy: {
|
||||||
|
quoteTime: 'desc',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const up = latestQuotes.filter((q) => q && q.changePercent > 0).length;
|
||||||
|
const down = latestQuotes.filter((q) => q && q.changePercent < 0).length;
|
||||||
|
const flat = latestQuotes.filter((q) => q && q.changePercent === 0).length;
|
||||||
|
|
||||||
|
const result = { up, down, flat };
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.upDownStats);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get up/down stats:', error);
|
||||||
|
return { up: 2850, down: 1950, flat: 200 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取涨跌幅分布
|
||||||
|
async getPriceDistribution(): Promise<PriceDistribution[]> {
|
||||||
|
const cacheKey = 'market:price:distribution';
|
||||||
|
const cached = await cache.get<PriceDistribution[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ranges = [
|
||||||
|
{ range: '<-7%', min: -100, max: -7, color: '#00c853' },
|
||||||
|
{ range: '-7~-5%', min: -7, max: -5, color: '#00e676' },
|
||||||
|
{ range: '-5~-3%', min: -5, max: -3, color: '#69f0ae' },
|
||||||
|
{ range: '-3~0%', min: -3, max: 0, color: '#b9f6ca' },
|
||||||
|
{ range: '0~3%', min: 0, max: 3, color: '#ffcdd2' },
|
||||||
|
{ range: '3~5%', min: 3, max: 5, color: '#ef9a9a' },
|
||||||
|
{ range: '5~7%', min: 5, max: 7, color: '#ef5350' },
|
||||||
|
{ range: '>7%', min: 7, max: 100, color: '#ff3b30' },
|
||||||
|
];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
|
||||||
|
|
||||||
|
const distribution = await Promise.all(
|
||||||
|
ranges.map(async (r) => {
|
||||||
|
const count = await prisma.stockQuote.count({
|
||||||
|
where: {
|
||||||
|
changePercent: {
|
||||||
|
gte: r.min,
|
||||||
|
lt: r.max,
|
||||||
|
},
|
||||||
|
quoteTime: {
|
||||||
|
gte: fiveMinutesAgo,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { ...r, count };
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
await cache.set(cacheKey, distribution, config.cacheTtl.priceDistribution);
|
||||||
|
return distribution;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get price distribution:', error);
|
||||||
|
// 返回模拟数据
|
||||||
|
return ranges.map((r) => ({
|
||||||
|
...r,
|
||||||
|
count: Math.floor(Math.random() * 800) + 50,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新市场指数
|
||||||
|
async updateMarketIndex(code: string, data: Partial<MarketIndex>): Promise<void> {
|
||||||
|
try {
|
||||||
|
await prisma.marketIndex.update({
|
||||||
|
where: { code },
|
||||||
|
data: {
|
||||||
|
current: data.current,
|
||||||
|
change: data.change,
|
||||||
|
changePercent: data.changePercent,
|
||||||
|
volume: BigInt(data.volume || 0),
|
||||||
|
turnover: BigInt(data.turnover || 0),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 清除缓存
|
||||||
|
await cache.del('market:indices');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to update market index ${code}:`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const marketService = new MarketService();
|
||||||
@ -0,0 +1,320 @@
|
|||||||
|
import prisma from '../config/database';
|
||||||
|
import { cache } from '../config/redis';
|
||||||
|
import config from '../config';
|
||||||
|
import { Sector, SectorMomentumHistory, MomentumStock } from '../types';
|
||||||
|
import { calculateSectorMomentum } from '../utils/maCalculator';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class SectorService {
|
||||||
|
// 获取版块列表(带动量排名)
|
||||||
|
async getSectorsWithMomentum(): Promise<Sector[]> {
|
||||||
|
const cacheKey = 'sectors:momentum';
|
||||||
|
const cached = await cache.get<Sector[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const sectors = await prisma.sector.findMany({
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 计算动量分数和排名
|
||||||
|
const sectorsWithMomentum: Sector[] = sectors.map((sector) => {
|
||||||
|
const latestQuote = sector.quotes[0];
|
||||||
|
const previousQuote = sector.quotes[1];
|
||||||
|
|
||||||
|
const volume = latestQuote?.volume ? Number(latestQuote.volume) : 0;
|
||||||
|
const avgVolume = previousQuote?.volume ? Number(previousQuote.volume) : volume;
|
||||||
|
|
||||||
|
const momentumScore = calculateSectorMomentum(
|
||||||
|
latestQuote?.changePercent || 0,
|
||||||
|
volume,
|
||||||
|
avgVolume
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: sector.name,
|
||||||
|
code: sector.code,
|
||||||
|
change: latestQuote?.change || 0,
|
||||||
|
changePercent: latestQuote?.changePercent || 0,
|
||||||
|
volume,
|
||||||
|
turnover: latestQuote?.turnover ? Number(latestQuote.turnover) : 0,
|
||||||
|
leadingStock: sector.name, // 可以从关联数据中获取
|
||||||
|
momentumScore,
|
||||||
|
rank: 0, // 稍后计算
|
||||||
|
previousRank: previousQuote?.rank || 0,
|
||||||
|
rankChange: 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// 按动量分数排序并分配排名
|
||||||
|
sectorsWithMomentum.sort((a, b) => (b.momentumScore || 0) - (a.momentumScore || 0));
|
||||||
|
sectorsWithMomentum.forEach((sector, index) => {
|
||||||
|
sector.rank = index + 1;
|
||||||
|
sector.rankChange = (sector.previousRank || 0) - sector.rank;
|
||||||
|
});
|
||||||
|
|
||||||
|
await cache.set(cacheKey, sectorsWithMomentum, config.cacheTtl.sectors);
|
||||||
|
return sectorsWithMomentum;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get sectors with momentum:', error);
|
||||||
|
return this.getDefaultSectors();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取默认版块数据
|
||||||
|
private getDefaultSectors(): Sector[] {
|
||||||
|
const sectors = [
|
||||||
|
'半导体', '新能源', '医药生物', '白酒', '银行', '证券', '保险',
|
||||||
|
'房地产', '汽车', '电子', '计算机', '通信', '传媒', '军工',
|
||||||
|
'有色金属', '钢铁', '煤炭', '化工', '建筑材料', '机械设备',
|
||||||
|
];
|
||||||
|
|
||||||
|
return sectors.map((name, index) => ({
|
||||||
|
name,
|
||||||
|
code: `880${String(index + 1).padStart(3, '0')}`,
|
||||||
|
change: Math.random() * 20 - 10,
|
||||||
|
changePercent: Math.random() * 5 - 2,
|
||||||
|
volume: Math.floor(Math.random() * 90000000) + 10000000,
|
||||||
|
turnover: Math.floor(Math.random() * 900000000) + 100000000,
|
||||||
|
leadingStock: `${name}龙头`,
|
||||||
|
momentumScore: Math.random() * 60 + 30,
|
||||||
|
rank: index + 1,
|
||||||
|
previousRank: Math.floor(Math.random() * 20) + 1,
|
||||||
|
rankChange: Math.floor(Math.random() * 10) - 5,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取版块详情
|
||||||
|
async getSectorDetail(sectorCode: string): Promise<Sector | null> {
|
||||||
|
const cacheKey = `sector:${sectorCode}:detail`;
|
||||||
|
const cached = await cache.get<Sector>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const sector = await prisma.sector.findUnique({
|
||||||
|
where: { code: sectorCode },
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sector) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const latestQuote = sector.quotes[0];
|
||||||
|
const previousQuote = sector.quotes[1];
|
||||||
|
|
||||||
|
const result: Sector = {
|
||||||
|
name: sector.name,
|
||||||
|
code: sector.code,
|
||||||
|
change: latestQuote?.change || 0,
|
||||||
|
changePercent: latestQuote?.changePercent || 0,
|
||||||
|
volume: latestQuote?.volume ? Number(latestQuote.volume) : 0,
|
||||||
|
turnover: latestQuote?.turnover ? Number(latestQuote.turnover) : 0,
|
||||||
|
momentumScore: latestQuote?.momentumScore || 50,
|
||||||
|
rank: latestQuote?.rank || 0,
|
||||||
|
previousRank: previousQuote?.rank || 0,
|
||||||
|
rankChange: (previousQuote?.rank || 0) - (latestQuote?.rank || 0),
|
||||||
|
};
|
||||||
|
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.sectorDetail);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to get sector detail ${sectorCode}:`, error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取版块历史排名
|
||||||
|
async getSectorRankHistory(sectorCode: string, days: number = 30): Promise<SectorMomentumHistory[]> {
|
||||||
|
const cacheKey = `sector:${sectorCode}:rank:history:${days}`;
|
||||||
|
const cached = await cache.get<SectorMomentumHistory[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const history = await prisma.sectorQuote.findMany({
|
||||||
|
where: {
|
||||||
|
sectorCode,
|
||||||
|
quoteTime: {
|
||||||
|
gte: new Date(Date.now() - days * 24 * 60 * 60 * 1000),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { quoteTime: 'asc' },
|
||||||
|
select: {
|
||||||
|
quoteTime: true,
|
||||||
|
rank: true,
|
||||||
|
momentumScore: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result: SectorMomentumHistory[] = history.map((h) => ({
|
||||||
|
date: h.quoteTime.toISOString().split('T')[0],
|
||||||
|
rank: h.rank,
|
||||||
|
momentumScore: h.momentumScore,
|
||||||
|
topStock: '', // 可以从其他表获取
|
||||||
|
}));
|
||||||
|
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.sectorDetail);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to get sector rank history ${sectorCode}:`, error);
|
||||||
|
return this.generateMockRankHistory(days);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成模拟历史数据
|
||||||
|
private generateMockRankHistory(days: number): SectorMomentumHistory[] {
|
||||||
|
const history: SectorMomentumHistory[] = [];
|
||||||
|
const today = new Date();
|
||||||
|
let currentRank = Math.floor(Math.random() * 20) + 1;
|
||||||
|
let currentScore = Math.random() * 40 + 50;
|
||||||
|
|
||||||
|
for (let i = days; i >= 0; i--) {
|
||||||
|
const date = new Date(today);
|
||||||
|
date.setDate(date.getDate() - i);
|
||||||
|
|
||||||
|
const rankChange = Math.floor(Math.random() * 7) - 3;
|
||||||
|
currentRank = Math.max(1, Math.min(20, currentRank + rankChange));
|
||||||
|
|
||||||
|
const scoreChange = Math.random() * 10 - 5;
|
||||||
|
currentScore = Math.max(30, Math.min(100, currentScore + scoreChange));
|
||||||
|
|
||||||
|
history.push({
|
||||||
|
date: date.toISOString().split('T')[0],
|
||||||
|
rank: currentRank,
|
||||||
|
momentumScore: Number(currentScore.toFixed(2)),
|
||||||
|
topStock: `股票${Math.floor(Math.random() * 100)}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return history;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取版块内股票
|
||||||
|
async getSectorStocks(sectorCode: string, limit: number = 20): Promise<any[]> {
|
||||||
|
try {
|
||||||
|
const stocks = await prisma.stock.findMany({
|
||||||
|
where: { sectorCode },
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
take: limit,
|
||||||
|
});
|
||||||
|
|
||||||
|
return stocks.map((stock) => ({
|
||||||
|
code: stock.code,
|
||||||
|
name: stock.name,
|
||||||
|
price: stock.quotes[0]?.price || 0,
|
||||||
|
change: stock.quotes[0]?.change || 0,
|
||||||
|
changePercent: stock.quotes[0]?.changePercent || 0,
|
||||||
|
volume: stock.quotes[0]?.volume ? Number(stock.quotes[0].volume) : 0,
|
||||||
|
turnover: stock.quotes[0]?.turnover ? Number(stock.quotes[0].turnover) : 0,
|
||||||
|
marketCap: stock.marketCap ? Number(stock.marketCap) : 0,
|
||||||
|
pe: stock.pe,
|
||||||
|
pb: stock.pb,
|
||||||
|
industry: stock.sector?.name,
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to get sector stocks ${sectorCode}:`, error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取版块内动量个股
|
||||||
|
async getSectorMomentumStocks(sectorCode: string): Promise<MomentumStock[]> {
|
||||||
|
try {
|
||||||
|
const stocks = await prisma.stock.findMany({
|
||||||
|
where: { sectorCode },
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 2,
|
||||||
|
},
|
||||||
|
momentumRecords: {
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const tags = ['强势突破', '量价齐升', '趋势反转', '资金流入', '技术金叉'];
|
||||||
|
|
||||||
|
return stocks
|
||||||
|
.map((stock) => {
|
||||||
|
const quote = stock.quotes[0];
|
||||||
|
const momentumRecord = stock.momentumRecords[0];
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: stock.code,
|
||||||
|
name: stock.name,
|
||||||
|
price: quote?.price || 0,
|
||||||
|
change: quote?.change || 0,
|
||||||
|
changePercent: quote?.changePercent || 0,
|
||||||
|
volume: quote?.volume ? Number(quote.volume) : 0,
|
||||||
|
turnover: quote?.turnover ? Number(quote.turnover) : 0,
|
||||||
|
industry: stock.sector?.name || '',
|
||||||
|
momentumScore: momentumRecord?.momentumScore || Math.floor(Math.random() * 50) + 50,
|
||||||
|
tags: momentumRecord?.tags ? JSON.parse(momentumRecord.tags) : [tags[Math.floor(Math.random() * tags.length)]],
|
||||||
|
volumeRatio: momentumRecord?.volumeRatio || Math.random() * 6 + 1.5,
|
||||||
|
breakThrough: momentumRecord?.breakThrough || Math.random() > 0.6,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.momentumScore - a.momentumScore);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to get sector momentum stocks ${sectorCode}:`, error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新版块排名
|
||||||
|
async updateSectorRankings(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const sectors = await this.getSectorsWithMomentum();
|
||||||
|
|
||||||
|
// 批量更新排名
|
||||||
|
await Promise.all(
|
||||||
|
sectors.map((sector, index) =>
|
||||||
|
prisma.sectorQuote.updateMany({
|
||||||
|
where: {
|
||||||
|
sectorCode: sector.code,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
rank: index + 1,
|
||||||
|
momentumScore: sector.momentumScore || 50,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// 清除缓存
|
||||||
|
await cache.delPattern('sectors:*');
|
||||||
|
|
||||||
|
logger.info('Sector rankings updated successfully');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to update sector rankings:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const sectorService = new SectorService();
|
||||||
@ -0,0 +1,469 @@
|
|||||||
|
import prisma from '../config/database';
|
||||||
|
import { cache } from '../config/redis';
|
||||||
|
import config from '../config';
|
||||||
|
import {
|
||||||
|
Stock,
|
||||||
|
StockDetail,
|
||||||
|
KLineData,
|
||||||
|
HighLowStock,
|
||||||
|
MomentumStock
|
||||||
|
} from '../types';
|
||||||
|
import { calculateMA, calculateIndicators, calculateMomentumScore } from '../utils/maCalculator';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class StockService {
|
||||||
|
// 搜索股票
|
||||||
|
async searchStocks(keyword: string): Promise<Stock[]> {
|
||||||
|
const cacheKey = `search:stocks:${keyword}`;
|
||||||
|
const cached = await cache.get<Stock[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stocks = await prisma.stock.findMany({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ name: { contains: keyword } },
|
||||||
|
{ code: { contains: keyword } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
take: 10,
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
sector: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result: Stock[] = stocks.map((s) => ({
|
||||||
|
code: s.code,
|
||||||
|
name: s.name,
|
||||||
|
price: s.quotes[0]?.price || 0,
|
||||||
|
change: s.quotes[0]?.change || 0,
|
||||||
|
changePercent: s.quotes[0]?.changePercent || 0,
|
||||||
|
volume: s.quotes[0]?.volume ? Number(s.quotes[0].volume) : 0,
|
||||||
|
turnover: s.quotes[0]?.turnover ? Number(s.quotes[0].turnover) : 0,
|
||||||
|
marketCap: s.marketCap ? Number(s.marketCap) : undefined,
|
||||||
|
pe: s.pe || undefined,
|
||||||
|
pb: s.pb || undefined,
|
||||||
|
industry: s.sector?.name,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.searchResults);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to search stocks with keyword ${keyword}:`, error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 搜索版块
|
||||||
|
async searchSectors(keyword: string): Promise<any[]> {
|
||||||
|
const cacheKey = `search:sectors:${keyword}`;
|
||||||
|
const cached = await cache.get<any[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const sectors = await prisma.sector.findMany({
|
||||||
|
where: {
|
||||||
|
name: { contains: keyword },
|
||||||
|
},
|
||||||
|
take: 10,
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = sectors.map((s) => ({
|
||||||
|
name: s.name,
|
||||||
|
code: s.code,
|
||||||
|
changePercent: s.quotes[0]?.changePercent || 0,
|
||||||
|
rank: s.quotes[0]?.rank || 0,
|
||||||
|
momentumScore: s.quotes[0]?.momentumScore || 50,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.searchResults);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to search sectors with keyword ${keyword}:`, error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取个股详情
|
||||||
|
async getStockDetail(code: string): Promise<StockDetail | null> {
|
||||||
|
const cacheKey = `stock:${code}:detail`;
|
||||||
|
const cached = await cache.get<StockDetail>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stock = await prisma.stock.findUnique({
|
||||||
|
where: { code },
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
sector: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!stock) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const klines = await this.getKLineData(code, 'day', 60);
|
||||||
|
const indicators = calculateIndicators(klines);
|
||||||
|
|
||||||
|
const result: StockDetail = {
|
||||||
|
code: stock.code,
|
||||||
|
name: stock.name,
|
||||||
|
price: stock.quotes[0]?.price || 0,
|
||||||
|
change: stock.quotes[0]?.change || 0,
|
||||||
|
changePercent: stock.quotes[0]?.changePercent || 0,
|
||||||
|
volume: stock.quotes[0]?.volume ? Number(stock.quotes[0].volume) : 0,
|
||||||
|
turnover: stock.quotes[0]?.turnover ? Number(stock.quotes[0].turnover) : 0,
|
||||||
|
marketCap: stock.marketCap ? Number(stock.marketCap) : 0,
|
||||||
|
pe: stock.pe || 0,
|
||||||
|
pb: stock.pb || 0,
|
||||||
|
industry: stock.sector?.name || '',
|
||||||
|
open: stock.quotes[0]?.open || 0,
|
||||||
|
high: stock.quotes[0]?.high || 0,
|
||||||
|
low: stock.quotes[0]?.low || 0,
|
||||||
|
preClose: stock.quotes[0]?.preClose || 0,
|
||||||
|
amplitude: stock.quotes[0]?.amplitude || 0,
|
||||||
|
turnoverRate: stock.quotes[0]?.turnoverRate || 0,
|
||||||
|
...indicators,
|
||||||
|
};
|
||||||
|
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.stockDetail);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to get stock detail ${code}:`, error);
|
||||||
|
return this.getMockStockDetail(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取模拟个股详情
|
||||||
|
private getMockStockDetail(code: string): StockDetail {
|
||||||
|
const price = Math.random() * 200 + 10;
|
||||||
|
const changePercent = Math.random() * 10 - 5;
|
||||||
|
const change = price * changePercent / 100;
|
||||||
|
|
||||||
|
return {
|
||||||
|
code,
|
||||||
|
name: `股票${code}`,
|
||||||
|
price: Number(price.toFixed(2)),
|
||||||
|
change: Number(change.toFixed(2)),
|
||||||
|
changePercent: Number(changePercent.toFixed(2)),
|
||||||
|
volume: Math.floor(Math.random() * 50000000) + 1000000,
|
||||||
|
turnover: Math.floor(Math.random() * 500000000) + 10000000,
|
||||||
|
marketCap: Math.floor(Math.random() * 500000000000) + 5000000000,
|
||||||
|
pe: Math.random() * 80 + 5,
|
||||||
|
pb: Math.random() * 15 + 0.5,
|
||||||
|
industry: '未知行业',
|
||||||
|
open: price * (1 + Math.random() * 0.04 - 0.02),
|
||||||
|
high: price * (1 + Math.random() * 0.05),
|
||||||
|
low: price * (1 - Math.random() * 0.05),
|
||||||
|
preClose: price - change,
|
||||||
|
amplitude: Math.random() * 8 + 1,
|
||||||
|
turnoverRate: Math.random() * 15 + 0.5,
|
||||||
|
macd: { dif: Math.random() * 4 - 2, dea: Math.random() * 4 - 2, macd: Math.random() * 2 - 1 },
|
||||||
|
kdj: { k: Math.random() * 100, d: Math.random() * 100, j: Math.random() * 120 - 20 },
|
||||||
|
rsi: { rsi6: Math.random() * 100, rsi12: Math.random() * 100, rsi24: Math.random() * 100 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取K线数据
|
||||||
|
async getKLineData(code: string, period: string = 'day', days: number = 60): Promise<KLineData[]> {
|
||||||
|
const cacheKey = `stock:${code}:kline:${period}:${days}`;
|
||||||
|
const cached = await cache.get<KLineData[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const klines = await prisma.stockKLine.findMany({
|
||||||
|
where: {
|
||||||
|
stockCode: code,
|
||||||
|
period,
|
||||||
|
},
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
take: days,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (klines.length === 0) {
|
||||||
|
return this.generateMockKLineData(days);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算均线
|
||||||
|
const klinesWithMA = calculateMA(klines.reverse().map((k) => ({
|
||||||
|
date: k.date.toISOString().split('T')[0],
|
||||||
|
open: k.open,
|
||||||
|
high: k.high,
|
||||||
|
low: k.low,
|
||||||
|
close: k.close,
|
||||||
|
volume: Number(k.volume),
|
||||||
|
})));
|
||||||
|
|
||||||
|
await cache.set(cacheKey, klinesWithMA, config.cacheTtl.klineData);
|
||||||
|
return klinesWithMA;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to get kline data for ${code}:`, error);
|
||||||
|
return this.generateMockKLineData(days);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成模拟K线数据
|
||||||
|
private generateMockKLineData(days: number): KLineData[] {
|
||||||
|
const data: KLineData[] = [];
|
||||||
|
let basePrice = Math.random() * 200 + 20;
|
||||||
|
const today = new Date();
|
||||||
|
|
||||||
|
for (let i = days; i >= 0; i--) {
|
||||||
|
const date = new Date(today);
|
||||||
|
date.setDate(date.getDate() - i);
|
||||||
|
|
||||||
|
const change = Math.random() * 0.1 - 0.05;
|
||||||
|
const open = basePrice;
|
||||||
|
const close = basePrice * (1 + change);
|
||||||
|
const high = Math.max(open, close) * (1 + Math.random() * 0.03);
|
||||||
|
const low = Math.min(open, close) * (1 - Math.random() * 0.03);
|
||||||
|
|
||||||
|
data.push({
|
||||||
|
date: date.toISOString().split('T')[0],
|
||||||
|
open: Number(open.toFixed(2)),
|
||||||
|
high: Number(high.toFixed(2)),
|
||||||
|
low: Number(low.toFixed(2)),
|
||||||
|
close: Number(close.toFixed(2)),
|
||||||
|
volume: Math.floor(Math.random() * 50000000) + 1000000,
|
||||||
|
});
|
||||||
|
|
||||||
|
basePrice = close;
|
||||||
|
}
|
||||||
|
|
||||||
|
return calculateMA(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取新高股票
|
||||||
|
async getNewHighStocks(days: number = 20, limit: number = 20): Promise<HighLowStock[]> {
|
||||||
|
try {
|
||||||
|
const records = await prisma.highLowStock.findMany({
|
||||||
|
where: {
|
||||||
|
type: 'high',
|
||||||
|
date: {
|
||||||
|
gte: new Date(Date.now() - days * 24 * 60 * 60 * 1000),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
take: limit,
|
||||||
|
include: {
|
||||||
|
stock: {
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
sector: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return records.map((record) => ({
|
||||||
|
code: record.stock.code,
|
||||||
|
name: record.stock.name,
|
||||||
|
price: record.stock.quotes[0]?.price || record.price,
|
||||||
|
change: record.stock.quotes[0]?.change || 0,
|
||||||
|
changePercent: record.stock.quotes[0]?.changePercent || 0,
|
||||||
|
volume: record.stock.quotes[0]?.volume ? Number(record.stock.quotes[0].volume) : 0,
|
||||||
|
turnover: record.stock.quotes[0]?.turnover ? Number(record.stock.quotes[0].turnover) : 0,
|
||||||
|
industry: record.stock.sector?.name || '',
|
||||||
|
highLowPrice: record.price,
|
||||||
|
date: record.date.toISOString().split('T')[0],
|
||||||
|
daysToHighLow: record.daysToHighLow,
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get new high stocks:', error);
|
||||||
|
return this.generateMockHighLowStocks('high', limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取新低股票
|
||||||
|
async getNewLowStocks(days: number = 20, limit: number = 20): Promise<HighLowStock[]> {
|
||||||
|
try {
|
||||||
|
const records = await prisma.highLowStock.findMany({
|
||||||
|
where: {
|
||||||
|
type: 'low',
|
||||||
|
date: {
|
||||||
|
gte: new Date(Date.now() - days * 24 * 60 * 60 * 1000),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { date: 'desc' },
|
||||||
|
take: limit,
|
||||||
|
include: {
|
||||||
|
stock: {
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
sector: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return records.map((record) => ({
|
||||||
|
code: record.stock.code,
|
||||||
|
name: record.stock.name,
|
||||||
|
price: record.stock.quotes[0]?.price || record.price,
|
||||||
|
change: record.stock.quotes[0]?.change || 0,
|
||||||
|
changePercent: record.stock.quotes[0]?.changePercent || 0,
|
||||||
|
volume: record.stock.quotes[0]?.volume ? Number(record.stock.quotes[0].volume) : 0,
|
||||||
|
turnover: record.stock.quotes[0]?.turnover ? Number(record.stock.quotes[0].turnover) : 0,
|
||||||
|
industry: record.stock.sector?.name || '',
|
||||||
|
highLowPrice: record.price,
|
||||||
|
date: record.date.toISOString().split('T')[0],
|
||||||
|
daysToHighLow: record.daysToHighLow,
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get new low stocks:', error);
|
||||||
|
return this.generateMockHighLowStocks('low', limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成模拟高低股票数据
|
||||||
|
private generateMockHighLowStocks(type: 'high' | 'low', limit: number): HighLowStock[] {
|
||||||
|
const industries = ['半导体', '新能源', '医药生物', '白酒', '银行', '证券', '保险'];
|
||||||
|
const stocks: HighLowStock[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < limit; i++) {
|
||||||
|
const price = type === 'high'
|
||||||
|
? Math.random() * 300 + 20
|
||||||
|
: Math.random() * 100 + 2;
|
||||||
|
const changePercent = type === 'high'
|
||||||
|
? Math.random() * 8 + 2
|
||||||
|
: Math.random() * -8 - 2;
|
||||||
|
|
||||||
|
stocks.push({
|
||||||
|
code: `60${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
|
||||||
|
name: `${industries[i % industries.length]}${String.fromCharCode(65 + i)}`,
|
||||||
|
price: Number(price.toFixed(2)),
|
||||||
|
change: Number((price * changePercent / 100).toFixed(2)),
|
||||||
|
changePercent: Number(changePercent.toFixed(2)),
|
||||||
|
volume: Math.floor(Math.random() * 50000000) + 1000000,
|
||||||
|
turnover: Math.floor(Math.random() * 500000000) + 10000000,
|
||||||
|
industry: industries[i % industries.length],
|
||||||
|
highLowPrice: Number(price.toFixed(2)),
|
||||||
|
date: new Date().toISOString().split('T')[0],
|
||||||
|
daysToHighLow: Math.floor(Math.random() * 252) + 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return stocks.sort((a, b) =>
|
||||||
|
type === 'high'
|
||||||
|
? b.changePercent - a.changePercent
|
||||||
|
: a.changePercent - b.changePercent
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取动量股推荐
|
||||||
|
async getMomentumStocks(limit: number = 15): Promise<MomentumStock[]> {
|
||||||
|
const cacheKey = `stocks:momentum:${limit}`;
|
||||||
|
const cached = await cache.get<MomentumStock[]>(cacheKey);
|
||||||
|
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const records = await prisma.momentumStock.findMany({
|
||||||
|
where: {
|
||||||
|
date: {
|
||||||
|
gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { momentumScore: 'desc' },
|
||||||
|
take: limit,
|
||||||
|
include: {
|
||||||
|
stock: {
|
||||||
|
include: {
|
||||||
|
quotes: {
|
||||||
|
orderBy: { quoteTime: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
sector: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result: MomentumStock[] = records.map((record) => ({
|
||||||
|
code: record.stock.code,
|
||||||
|
name: record.stock.name,
|
||||||
|
price: record.stock.quotes[0]?.price || 0,
|
||||||
|
change: record.stock.quotes[0]?.change || 0,
|
||||||
|
changePercent: record.stock.quotes[0]?.changePercent || 0,
|
||||||
|
volume: record.stock.quotes[0]?.volume ? Number(record.stock.quotes[0].volume) : 0,
|
||||||
|
turnover: record.stock.quotes[0]?.turnover ? Number(record.stock.quotes[0].turnover) : 0,
|
||||||
|
industry: record.stock.sector?.name || '',
|
||||||
|
momentumScore: record.momentumScore,
|
||||||
|
tags: record.tags ? JSON.parse(record.tags) : [],
|
||||||
|
volumeRatio: record.volumeRatio,
|
||||||
|
breakThrough: record.breakThrough,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await cache.set(cacheKey, result, config.cacheTtl.sectors);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get momentum stocks:', error);
|
||||||
|
return this.generateMockMomentumStocks(limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成模拟动量股数据
|
||||||
|
private generateMockMomentumStocks(limit: number): MomentumStock[] {
|
||||||
|
const industries = ['半导体', '新能源', '医药生物', '白酒', '银行', '证券', '保险'];
|
||||||
|
const tags = ['强势突破', '量价齐升', '趋势反转', '资金流入', '技术金叉'];
|
||||||
|
const stocks: MomentumStock[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < limit; i++) {
|
||||||
|
const price = Math.random() * 200 + 10;
|
||||||
|
const changePercent = Math.random() * 9 + 3;
|
||||||
|
|
||||||
|
stocks.push({
|
||||||
|
code: `60${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
|
||||||
|
name: `${industries[i % industries.length]}${String.fromCharCode(65 + i)}`,
|
||||||
|
price: Number(price.toFixed(2)),
|
||||||
|
change: Number((price * changePercent / 100).toFixed(2)),
|
||||||
|
changePercent: Number(changePercent.toFixed(2)),
|
||||||
|
volume: Math.floor(Math.random() * 80000000) + 2000000,
|
||||||
|
turnover: Math.floor(Math.random() * 1000000000) + 50000000,
|
||||||
|
industry: industries[i % industries.length],
|
||||||
|
momentumScore: Math.floor(Math.random() * 40) + 60,
|
||||||
|
tags: [tags[Math.floor(Math.random() * tags.length)]],
|
||||||
|
volumeRatio: Math.random() * 6 + 1.5,
|
||||||
|
breakThrough: Math.random() > 0.5,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return stocks.sort((a, b) => b.momentumScore - a.momentumScore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const stockService = new StockService();
|
||||||
@ -0,0 +1,186 @@
|
|||||||
|
// 股票基础信息
|
||||||
|
export interface Stock {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
price: number;
|
||||||
|
change: number;
|
||||||
|
changePercent: number;
|
||||||
|
volume: number;
|
||||||
|
turnover: number;
|
||||||
|
marketCap?: number;
|
||||||
|
pe?: number;
|
||||||
|
pb?: number;
|
||||||
|
industry?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 版块信息
|
||||||
|
export interface Sector {
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
change: number;
|
||||||
|
changePercent: number;
|
||||||
|
volume: number;
|
||||||
|
turnover: number;
|
||||||
|
leadingStock?: string;
|
||||||
|
momentumScore?: number;
|
||||||
|
rank?: number;
|
||||||
|
previousRank?: number;
|
||||||
|
rankChange?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 市场指数
|
||||||
|
export interface MarketIndex {
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
current: number;
|
||||||
|
change: number;
|
||||||
|
changePercent: number;
|
||||||
|
volume: number;
|
||||||
|
turnover: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// K线数据
|
||||||
|
export interface KLineData {
|
||||||
|
date: string;
|
||||||
|
open: number;
|
||||||
|
high: number;
|
||||||
|
low: number;
|
||||||
|
close: number;
|
||||||
|
volume: number;
|
||||||
|
ma5?: number;
|
||||||
|
ma10?: number;
|
||||||
|
ma20?: number;
|
||||||
|
ma30?: number;
|
||||||
|
ma60?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 新高新低股票
|
||||||
|
export interface HighLowStock extends Stock {
|
||||||
|
highLowPrice: number;
|
||||||
|
date: string;
|
||||||
|
daysToHighLow: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 动量股票
|
||||||
|
export interface MomentumStock extends Stock {
|
||||||
|
momentumScore: number;
|
||||||
|
tags: string[];
|
||||||
|
volumeRatio: number;
|
||||||
|
breakThrough: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 涨跌分布
|
||||||
|
export interface PriceDistribution {
|
||||||
|
range: string;
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
count: number;
|
||||||
|
color?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 版块历史排名
|
||||||
|
export interface SectorMomentumHistory {
|
||||||
|
date: string;
|
||||||
|
rank: number;
|
||||||
|
momentumScore: number;
|
||||||
|
topStock?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 个股详情
|
||||||
|
export interface StockDetail extends Stock {
|
||||||
|
open: number;
|
||||||
|
high: number;
|
||||||
|
low: number;
|
||||||
|
preClose: number;
|
||||||
|
amplitude: number;
|
||||||
|
turnoverRate: number;
|
||||||
|
macd: {
|
||||||
|
dif: number;
|
||||||
|
dea: number;
|
||||||
|
macd: number;
|
||||||
|
};
|
||||||
|
kdj: {
|
||||||
|
k: number;
|
||||||
|
d: number;
|
||||||
|
j: number;
|
||||||
|
};
|
||||||
|
rsi: {
|
||||||
|
rsi6: number;
|
||||||
|
rsi12: number;
|
||||||
|
rsi24: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用户
|
||||||
|
export interface User {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
// API响应格式
|
||||||
|
export interface ApiResponse<T = any> {
|
||||||
|
code: number;
|
||||||
|
message: string;
|
||||||
|
data: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebSocket消息
|
||||||
|
export interface WebSocketMessage {
|
||||||
|
channel: string;
|
||||||
|
type: string;
|
||||||
|
data: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 均线周期配置
|
||||||
|
export interface MaPeriod {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
days: number;
|
||||||
|
color: string;
|
||||||
|
visible: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 技术指标
|
||||||
|
export interface TechnicalIndicators {
|
||||||
|
macd: {
|
||||||
|
dif: number;
|
||||||
|
dea: number;
|
||||||
|
macd: number;
|
||||||
|
};
|
||||||
|
kdj: {
|
||||||
|
k: number;
|
||||||
|
d: number;
|
||||||
|
j: number;
|
||||||
|
};
|
||||||
|
rsi: {
|
||||||
|
rsi6: number;
|
||||||
|
rsi12: number;
|
||||||
|
rsi24: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// AKShare数据格式
|
||||||
|
export interface AKShareStockSpot {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
price: number;
|
||||||
|
change: number;
|
||||||
|
change_percent: number;
|
||||||
|
volume: number;
|
||||||
|
turnover: number;
|
||||||
|
open: number;
|
||||||
|
high: number;
|
||||||
|
low: number;
|
||||||
|
pre_close: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AKShareKLine {
|
||||||
|
date: string;
|
||||||
|
open: number;
|
||||||
|
high: number;
|
||||||
|
low: number;
|
||||||
|
close: number;
|
||||||
|
volume: number;
|
||||||
|
}
|
||||||
@ -0,0 +1,111 @@
|
|||||||
|
import winston from 'winston';
|
||||||
|
import DailyRotateFile from 'winston-daily-rotate-file';
|
||||||
|
import path from 'path';
|
||||||
|
import config from '../config';
|
||||||
|
|
||||||
|
const { combine, timestamp, printf, colorize, errors } = winston.format;
|
||||||
|
|
||||||
|
// 自定义日志格式
|
||||||
|
const logFormat = printf(({ level, message, timestamp, stack, ...metadata }) => {
|
||||||
|
let msg = `${timestamp} [${level}]: ${message}`;
|
||||||
|
if (Object.keys(metadata).length > 0) {
|
||||||
|
msg += ` ${JSON.stringify(metadata)}`;
|
||||||
|
}
|
||||||
|
if (stack) {
|
||||||
|
msg += `\n${stack}`;
|
||||||
|
}
|
||||||
|
return msg;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 创建日志目录
|
||||||
|
const logDir = path.resolve(config.logDir);
|
||||||
|
|
||||||
|
// 控制台输出格式
|
||||||
|
const consoleFormat = combine(
|
||||||
|
colorize(),
|
||||||
|
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||||
|
errors({ stack: true }),
|
||||||
|
logFormat
|
||||||
|
);
|
||||||
|
|
||||||
|
// 文件输出格式
|
||||||
|
const fileFormat = combine(
|
||||||
|
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||||
|
errors({ stack: true }),
|
||||||
|
logFormat
|
||||||
|
);
|
||||||
|
|
||||||
|
// 创建 logger
|
||||||
|
const logger = winston.createLogger({
|
||||||
|
level: config.logLevel,
|
||||||
|
defaultMeta: { service: 'aguzhitou-api' },
|
||||||
|
transports: [
|
||||||
|
// 控制台输出
|
||||||
|
new winston.transports.Console({
|
||||||
|
format: consoleFormat,
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 信息日志文件
|
||||||
|
new DailyRotateFile({
|
||||||
|
filename: path.join(logDir, 'info-%DATE%.log'),
|
||||||
|
datePattern: 'YYYY-MM-DD',
|
||||||
|
level: 'info',
|
||||||
|
format: fileFormat,
|
||||||
|
maxSize: '20m',
|
||||||
|
maxFiles: '14d',
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 错误日志文件
|
||||||
|
new DailyRotateFile({
|
||||||
|
filename: path.join(logDir, 'error-%DATE%.log'),
|
||||||
|
datePattern: 'YYYY-MM-DD',
|
||||||
|
level: 'error',
|
||||||
|
format: fileFormat,
|
||||||
|
maxSize: '20m',
|
||||||
|
maxFiles: '30d',
|
||||||
|
}),
|
||||||
|
|
||||||
|
// 所有日志文件
|
||||||
|
new DailyRotateFile({
|
||||||
|
filename: path.join(logDir, 'combined-%DATE%.log'),
|
||||||
|
datePattern: 'YYYY-MM-DD',
|
||||||
|
format: fileFormat,
|
||||||
|
maxSize: '50m',
|
||||||
|
maxFiles: '7d',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
// 未捕获的异常
|
||||||
|
exceptionHandlers: [
|
||||||
|
new DailyRotateFile({
|
||||||
|
filename: path.join(logDir, 'exceptions-%DATE%.log'),
|
||||||
|
datePattern: 'YYYY-MM-DD',
|
||||||
|
maxSize: '20m',
|
||||||
|
maxFiles: '30d',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
// 未处理的 Promise 拒绝
|
||||||
|
rejectionHandlers: [
|
||||||
|
new DailyRotateFile({
|
||||||
|
filename: path.join(logDir, 'rejections-%DATE%.log'),
|
||||||
|
datePattern: 'YYYY-MM-DD',
|
||||||
|
maxSize: '20m',
|
||||||
|
maxFiles: '30d',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 开发环境下简化日志输出
|
||||||
|
if (config.nodeEnv === 'development') {
|
||||||
|
logger.clear();
|
||||||
|
logger.add(new winston.transports.Console({
|
||||||
|
format: combine(
|
||||||
|
colorize(),
|
||||||
|
timestamp({ format: 'HH:mm:ss' }),
|
||||||
|
printf(({ level, message, timestamp }) => {
|
||||||
|
return `${timestamp} [${level}]: ${message}`;
|
||||||
|
})
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default logger;
|
||||||
@ -0,0 +1,74 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// 股票代码验证
|
||||||
|
export const stockCodeSchema = z.string()
|
||||||
|
.min(6)
|
||||||
|
.max(6)
|
||||||
|
.regex(/^[0-9]{6}$/, '股票代码必须是6位数字');
|
||||||
|
|
||||||
|
// 版块代码验证
|
||||||
|
export const sectorCodeSchema = z.string()
|
||||||
|
.min(6)
|
||||||
|
.max(6)
|
||||||
|
.regex(/^[0-9]{6}$/, '版块代码必须是6位数字');
|
||||||
|
|
||||||
|
// 日期范围验证
|
||||||
|
export const dateRangeSchema = z.object({
|
||||||
|
start: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, '日期格式必须是YYYY-MM-DD'),
|
||||||
|
end: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, '日期格式必须是YYYY-MM-DD'),
|
||||||
|
});
|
||||||
|
|
||||||
|
// K线周期验证
|
||||||
|
export const periodSchema = z.enum(['day', 'week', 'month']);
|
||||||
|
|
||||||
|
// 分页参数验证
|
||||||
|
export const paginationSchema = z.object({
|
||||||
|
page: z.string().optional().transform((val) => parseInt(val || '1', 10)),
|
||||||
|
limit: z.string().optional().transform((val) => parseInt(val || '20', 10)),
|
||||||
|
});
|
||||||
|
|
||||||
|
// 搜索关键词验证
|
||||||
|
export const searchKeywordSchema = z.string()
|
||||||
|
.min(1)
|
||||||
|
.max(50)
|
||||||
|
.transform((val) => val.trim());
|
||||||
|
|
||||||
|
// 用户注册验证
|
||||||
|
export const userRegisterSchema = z.object({
|
||||||
|
username: z.string().min(3).max(20).regex(/^[a-zA-Z0-9_]+$/),
|
||||||
|
email: z.string().email(),
|
||||||
|
password: z.string().min(6).max(50),
|
||||||
|
});
|
||||||
|
|
||||||
|
// 用户登录验证
|
||||||
|
export const userLoginSchema = z.object({
|
||||||
|
email: z.string().email(),
|
||||||
|
password: z.string().min(1),
|
||||||
|
});
|
||||||
|
|
||||||
|
// 自选股验证
|
||||||
|
export const favoriteStockSchema = z.object({
|
||||||
|
stockCode: stockCodeSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
// API响应验证
|
||||||
|
export const apiResponseSchema = <T extends z.ZodType>(dataSchema: T) =>
|
||||||
|
z.object({
|
||||||
|
code: z.number(),
|
||||||
|
message: z.string(),
|
||||||
|
data: dataSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证中间件辅助函数
|
||||||
|
export function validate<T>(schema: z.ZodSchema<T>, data: unknown): T {
|
||||||
|
return schema.parse(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 安全验证(不抛出错误)
|
||||||
|
export function safeValidate<T>(schema: z.ZodSchema<T>, data: unknown): { success: true; data: T } | { success: false; error: z.ZodError } {
|
||||||
|
const result = schema.safeParse(data);
|
||||||
|
if (result.success) {
|
||||||
|
return { success: true, data: result.data };
|
||||||
|
}
|
||||||
|
return { success: false, error: result.error };
|
||||||
|
}
|
||||||
@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "tests"]
|
||||||
|
}
|
||||||
@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "new-york",
|
||||||
|
"rsc": false,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "postcss.config.js",
|
||||||
|
"css": "src/index.css",
|
||||||
|
"baseColor": "slate",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
@ -0,0 +1,579 @@
|
|||||||
|
# A股智投分析平台 - 部署文档
|
||||||
|
|
||||||
|
## 一、前端部署
|
||||||
|
|
||||||
|
### 1.1 构建
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /mnt/okcomputer/output/app
|
||||||
|
|
||||||
|
# 安装依赖
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 开发模式
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 构建生产版本
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 构建输出
|
||||||
|
|
||||||
|
构建完成后,文件位于 `dist/` 目录:
|
||||||
|
|
||||||
|
```
|
||||||
|
dist/
|
||||||
|
├── index.html # 入口HTML
|
||||||
|
├── assets/
|
||||||
|
│ ├── index-xxx.js # JS bundle
|
||||||
|
│ ├── index-xxx.css # CSS bundle
|
||||||
|
│ └── ...
|
||||||
|
└── ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 部署方式
|
||||||
|
|
||||||
|
#### 方式一: 静态服务器
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用 serve
|
||||||
|
npx serve dist
|
||||||
|
|
||||||
|
# 使用 Python
|
||||||
|
python -m http.server 8080 --directory dist
|
||||||
|
|
||||||
|
# 使用 Nginx
|
||||||
|
cp -r dist/* /var/www/html/
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 方式二: Nginx 配置
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name aguzhitou.com;
|
||||||
|
|
||||||
|
root /var/www/aguzhitou;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /assets {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gzip压缩
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/plain text/css application/json application/javascript;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 方式三: CDN 部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 阿里云 OSS
|
||||||
|
ossutil cp -r dist/ oss://aguzhitou-bucket/
|
||||||
|
|
||||||
|
# 腾讯云 COS
|
||||||
|
coscmd upload -r dist/ /
|
||||||
|
|
||||||
|
# AWS S3
|
||||||
|
aws s3 sync dist/ s3://aguzhitou-bucket/
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 方式四: Docker 部署
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
# Dockerfile
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
COPY dist/ /usr/share/nginx/html/
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 构建镜像
|
||||||
|
docker build -t aguzhitou-frontend .
|
||||||
|
|
||||||
|
# 运行容器
|
||||||
|
docker run -d -p 80:80 --name aguzhitou-frontend aguzhitou-frontend
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、后端部署
|
||||||
|
|
||||||
|
### 2.1 环境准备
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 安装 Node.js 20
|
||||||
|
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||||
|
sudo apt-get install -y nodejs
|
||||||
|
|
||||||
|
# 安装 MySQL
|
||||||
|
sudo apt-get install mysql-server
|
||||||
|
|
||||||
|
# 安装 Redis
|
||||||
|
sudo apt-get install redis-server
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 数据库初始化
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 创建数据库
|
||||||
|
mysql -u root -p
|
||||||
|
|
||||||
|
CREATE DATABASE aguzhitou CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
CREATE USER 'aguzhitou'@'localhost' IDENTIFIED BY 'your-password';
|
||||||
|
GRANT ALL PRIVILEGES ON aguzhitou.* TO 'aguzhitou'@'localhost';
|
||||||
|
FLUSH PRIVILEGES;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 后端部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
|
||||||
|
# 安装依赖
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 生成 Prisma Client
|
||||||
|
npx prisma generate
|
||||||
|
|
||||||
|
# 执行数据库迁移
|
||||||
|
npx prisma migrate deploy
|
||||||
|
|
||||||
|
# 构建
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 启动
|
||||||
|
npm start
|
||||||
|
|
||||||
|
# 或使用 PM2
|
||||||
|
pm2 start dist/app.js --name aguzhitou-api
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 Docker Compose 部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 启动所有服务
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# 查看日志
|
||||||
|
docker-compose logs -f app
|
||||||
|
|
||||||
|
# 停止服务
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、完整部署架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ 用户 │
|
||||||
|
└─────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ CDN (静态资源) │
|
||||||
|
│ 阿里云/腾讯云/AWS │
|
||||||
|
└─────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ Nginx (负载均衡) │
|
||||||
|
│ 反向代理 + SSL │
|
||||||
|
└─────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌───────────────────┼───────────────────┐
|
||||||
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
|
||||||
|
│ Frontend 1 │ │ Frontend 2 │ │ Frontend 3 │
|
||||||
|
│ (Nginx) │ │ (Nginx) │ │ (Nginx) │
|
||||||
|
└────────┬─────────┘ └────────┬─────────┘ └────────┬─────────┘
|
||||||
|
│ │ │
|
||||||
|
└─────────────────────┼─────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────┐
|
||||||
|
│ Backend API │
|
||||||
|
│ (Node.js) │
|
||||||
|
│ x3 实例 │
|
||||||
|
└───────────┬──────────────┘
|
||||||
|
│
|
||||||
|
┌────────────────┼────────────────┐
|
||||||
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌──────────────────┐ ┌──────────────┐ ┌──────────────┐
|
||||||
|
│ MySQL 主从 │ │ Redis │ │ WebSocket │
|
||||||
|
│ (主库+从库) │ │ Cluster │ │ Server │
|
||||||
|
└──────────────────┘ └──────────────┘ └──────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、环境配置
|
||||||
|
|
||||||
|
### 4.1 生产环境变量
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# /etc/environment
|
||||||
|
|
||||||
|
# 应用配置
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# 数据库
|
||||||
|
DATABASE_URL=mysql://aguzhitou:password@localhost:3306/aguzhitou
|
||||||
|
|
||||||
|
# Redis
|
||||||
|
REDIS_URL=redis://localhost:6379
|
||||||
|
|
||||||
|
# JWT
|
||||||
|
JWT_SECRET=your-super-secret-key-min-32-characters
|
||||||
|
JWT_EXPIRES_IN=7d
|
||||||
|
|
||||||
|
# 日志
|
||||||
|
LOG_LEVEL=info
|
||||||
|
|
||||||
|
# 外部API
|
||||||
|
AKSHARE_URL=http://localhost:8000
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Nginx 完整配置
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
# /etc/nginx/nginx.conf
|
||||||
|
|
||||||
|
user nginx;
|
||||||
|
worker_processes auto;
|
||||||
|
error_log /var/log/nginx/error.log warn;
|
||||||
|
pid /var/run/nginx.pid;
|
||||||
|
|
||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
include /etc/nginx/mime.types;
|
||||||
|
default_type application/octet-stream;
|
||||||
|
|
||||||
|
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||||
|
'$status $body_bytes_sent "$http_referer" '
|
||||||
|
'"$http_user_agent" "$http_x_forwarded_for"';
|
||||||
|
|
||||||
|
access_log /var/log/nginx/access.log main;
|
||||||
|
|
||||||
|
sendfile on;
|
||||||
|
tcp_nopush on;
|
||||||
|
tcp_nodelay on;
|
||||||
|
keepalive_timeout 65;
|
||||||
|
types_hash_max_size 2048;
|
||||||
|
|
||||||
|
# Gzip
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_proxied any;
|
||||||
|
gzip_comp_level 6;
|
||||||
|
gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
|
||||||
|
|
||||||
|
# 前端
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name aguzhitou.com www.aguzhitou.com;
|
||||||
|
|
||||||
|
# 重定向到 HTTPS
|
||||||
|
return 301 https://$server_name$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name aguzhitou.com www.aguzhitou.com;
|
||||||
|
|
||||||
|
ssl_certificate /etc/nginx/ssl/aguzhitou.crt;
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/aguzhitou.key;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
root /var/www/aguzhitou;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
expires -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /assets {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
# API 代理
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://localhost:3000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
}
|
||||||
|
|
||||||
|
# WebSocket 代理
|
||||||
|
location /ws {
|
||||||
|
proxy_pass http://localhost:3001;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、SSL 证书配置
|
||||||
|
|
||||||
|
### 5.1 Let's Encrypt 免费证书
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 安装 Certbot
|
||||||
|
sudo apt-get install certbot python3-certbot-nginx
|
||||||
|
|
||||||
|
# 获取证书
|
||||||
|
sudo certbot --nginx -d aguzhitou.com -d www.aguzhitou.com
|
||||||
|
|
||||||
|
# 自动续期
|
||||||
|
sudo certbot renew --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 阿里云 SSL 证书
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 下载证书并放置到
|
||||||
|
/etc/nginx/ssl/
|
||||||
|
├── aguzhitou.crt
|
||||||
|
└── aguzhitou.key
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、监控与日志
|
||||||
|
|
||||||
|
### 6.1 PM2 进程管理
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 安装
|
||||||
|
npm install -g pm2
|
||||||
|
|
||||||
|
# 启动
|
||||||
|
pm2 start dist/app.js --name aguzhitou-api
|
||||||
|
|
||||||
|
# 查看状态
|
||||||
|
pm2 status
|
||||||
|
|
||||||
|
# 查看日志
|
||||||
|
pm2 logs aguzhitou-api
|
||||||
|
|
||||||
|
# 重启
|
||||||
|
pm2 restart aguzhitou-api
|
||||||
|
|
||||||
|
# 保存配置
|
||||||
|
pm2 save
|
||||||
|
pm2 startup
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 日志收集 (ELK)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# docker-compose.logging.yml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
elasticsearch:
|
||||||
|
image: docker.elastic.co/elasticsearch/elasticsearch:8.0.0
|
||||||
|
environment:
|
||||||
|
- discovery.type=single-node
|
||||||
|
volumes:
|
||||||
|
- es_data:/usr/share/elasticsearch/data
|
||||||
|
|
||||||
|
logstash:
|
||||||
|
image: docker.elastic.co/logstash/logstash:8.0.0
|
||||||
|
volumes:
|
||||||
|
- ./logstash.conf:/usr/share/logstash/pipeline/logstash.conf
|
||||||
|
|
||||||
|
kibana:
|
||||||
|
image: docker.elastic.co/kibana/kibana:8.0.0
|
||||||
|
ports:
|
||||||
|
- "5601:5601"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
es_data:
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 监控告警 (Prometheus + Grafana)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# docker-compose.monitoring.yml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus
|
||||||
|
volumes:
|
||||||
|
- ./prometheus.yml:/etc/prometheus/prometheus.yml
|
||||||
|
- prometheus_data:/prometheus
|
||||||
|
ports:
|
||||||
|
- "9090:9090"
|
||||||
|
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana
|
||||||
|
volumes:
|
||||||
|
- grafana_data:/var/lib/grafana
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
prometheus_data:
|
||||||
|
grafana_data:
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、备份策略
|
||||||
|
|
||||||
|
### 7.1 数据库备份
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
# backup.sh
|
||||||
|
|
||||||
|
BACKUP_DIR=/backup/mysql
|
||||||
|
DATE=$(date +%Y%m%d_%H%M%S)
|
||||||
|
|
||||||
|
# 备份
|
||||||
|
mysqldump -u root -p aguzhitou > $BACKUP_DIR/aguzhitou_$DATE.sql
|
||||||
|
|
||||||
|
# 压缩
|
||||||
|
gzip $BACKUP_DIR/aguzhitou_$DATE.sql
|
||||||
|
|
||||||
|
# 保留最近7天
|
||||||
|
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
|
||||||
|
|
||||||
|
# 上传到云存储
|
||||||
|
ossutil cp $BACKUP_DIR/aguzhitou_$DATE.sql.gz oss://aguzhitou-backup/
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 添加定时任务
|
||||||
|
crontab -e
|
||||||
|
|
||||||
|
# 每天凌晨2点备份
|
||||||
|
0 2 * * * /path/to/backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 Redis 备份
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 开启 RDB 持久化
|
||||||
|
# redis.conf
|
||||||
|
save 900 1
|
||||||
|
save 300 10
|
||||||
|
save 60 10000
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、故障排查
|
||||||
|
|
||||||
|
### 8.1 常见问题
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 端口被占用
|
||||||
|
sudo lsof -i :3000
|
||||||
|
sudo kill -9 <PID>
|
||||||
|
|
||||||
|
# 2. 数据库连接失败
|
||||||
|
mysql -u aguzhitou -p -h localhost
|
||||||
|
|
||||||
|
# 3. Redis 连接失败
|
||||||
|
redis-cli ping
|
||||||
|
|
||||||
|
# 4. 查看日志
|
||||||
|
tail -f /var/log/nginx/error.log
|
||||||
|
tail -f /var/log/aguzhitou/app.log
|
||||||
|
|
||||||
|
# 5. 内存不足
|
||||||
|
free -h
|
||||||
|
ps aux --sort=-%mem | head -10
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 性能优化
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# MySQL 优化
|
||||||
|
# /etc/mysql/mysql.conf.d/mysqld.cnf
|
||||||
|
[mysqld]
|
||||||
|
innodb_buffer_pool_size = 1G
|
||||||
|
max_connections = 200
|
||||||
|
query_cache_size = 64M
|
||||||
|
|
||||||
|
# Redis 优化
|
||||||
|
# /etc/redis/redis.conf
|
||||||
|
maxmemory 512mb
|
||||||
|
maxmemory-policy allkeys-lru
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、回滚策略
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 备份当前版本
|
||||||
|
cp -r /var/www/aguzhitou /var/www/aguzhitou-backup-$(date +%Y%m%d)
|
||||||
|
|
||||||
|
# 2. 部署新版本
|
||||||
|
npm run build
|
||||||
|
cp -r dist/* /var/www/aguzhitou/
|
||||||
|
|
||||||
|
# 3. 如果出现问题,回滚
|
||||||
|
cp -r /var/www/aguzhitou-backup-20240115/* /var/www/aguzhitou/
|
||||||
|
|
||||||
|
# 4. 重启服务
|
||||||
|
pm2 restart aguzhitou-api
|
||||||
|
sudo systemctl restart nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十、部署检查清单
|
||||||
|
|
||||||
|
- [ ] 服务器环境配置完成
|
||||||
|
- [ ] 数据库创建并初始化
|
||||||
|
- [ ] Redis 服务运行正常
|
||||||
|
- [ ] 后端服务部署成功
|
||||||
|
- [ ] 前端构建并部署
|
||||||
|
- [ ] Nginx 配置正确
|
||||||
|
- [ ] SSL 证书配置
|
||||||
|
- [ ] 域名解析正确
|
||||||
|
- [ ] 日志收集配置
|
||||||
|
- [ ] 监控告警配置
|
||||||
|
- [ ] 备份策略配置
|
||||||
|
- [ ] 性能测试通过
|
||||||
|
- [ ] 安全扫描通过
|
||||||
@ -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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>A股智投分析平台</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
Using Node.js 20, Tailwind CSS v3.4.19, and Vite v7.2.4
|
||||||
|
|
||||||
|
Tailwind CSS has been set up with the shadcn theme
|
||||||
|
|
||||||
|
Setup complete: /mnt/okcomputer/output/app
|
||||||
|
|
||||||
|
Components (40+):
|
||||||
|
accordion, alert-dialog, alert, aspect-ratio, avatar, badge, breadcrumb,
|
||||||
|
button-group, button, calendar, card, carousel, chart, checkbox, collapsible,
|
||||||
|
command, context-menu, dialog, drawer, dropdown-menu, empty, field, form,
|
||||||
|
hover-card, input-group, input-otp, input, item, kbd, label, menubar,
|
||||||
|
navigation-menu, pagination, popover, progress, radio-group, resizable,
|
||||||
|
scroll-area, select, separator, sheet, sidebar, skeleton, slider, sonner,
|
||||||
|
spinner, switch, table, tabs, textarea, toggle-group, toggle, tooltip
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
|
||||||
|
Structure:
|
||||||
|
src/sections/ Page sections
|
||||||
|
src/hooks/ Custom hooks
|
||||||
|
src/types/ Type definitions
|
||||||
|
src/App.css Styles specific to the Webapp
|
||||||
|
src/App.tsx Root React component
|
||||||
|
src/index.css Global styles
|
||||||
|
src/main.tsx Entry point for rendering the Webapp
|
||||||
|
index.html Entry point for the Webapp
|
||||||
|
tailwind.config.js Configures Tailwind's theme, plugins, etc.
|
||||||
|
vite.config.ts Main build and dev server settings for Vite
|
||||||
|
postcss.config.js Config file for CSS post-processing tools
|
||||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,80 @@
|
|||||||
|
{
|
||||||
|
"name": "my-app",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@hookform/resolvers": "^5.2.2",
|
||||||
|
"@radix-ui/react-accordion": "^1.2.12",
|
||||||
|
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-aspect-ratio": "^1.1.8",
|
||||||
|
"@radix-ui/react-avatar": "^1.1.11",
|
||||||
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
|
"@radix-ui/react-collapsible": "^1.1.12",
|
||||||
|
"@radix-ui/react-context-menu": "^2.2.16",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
|
"@radix-ui/react-hover-card": "^1.1.15",
|
||||||
|
"@radix-ui/react-label": "^2.1.8",
|
||||||
|
"@radix-ui/react-menubar": "^1.1.16",
|
||||||
|
"@radix-ui/react-navigation-menu": "^1.2.14",
|
||||||
|
"@radix-ui/react-popover": "^1.1.15",
|
||||||
|
"@radix-ui/react-progress": "^1.1.8",
|
||||||
|
"@radix-ui/react-radio-group": "^1.3.8",
|
||||||
|
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||||
|
"@radix-ui/react-select": "^2.2.6",
|
||||||
|
"@radix-ui/react-separator": "^1.1.8",
|
||||||
|
"@radix-ui/react-slider": "^1.3.6",
|
||||||
|
"@radix-ui/react-slot": "^1.2.4",
|
||||||
|
"@radix-ui/react-switch": "^1.2.6",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.13",
|
||||||
|
"@radix-ui/react-toggle": "^1.1.10",
|
||||||
|
"@radix-ui/react-toggle-group": "^1.1.11",
|
||||||
|
"@radix-ui/react-tooltip": "^1.2.8",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"cmdk": "^1.1.1",
|
||||||
|
"date-fns": "^4.1.0",
|
||||||
|
"embla-carousel-react": "^8.6.0",
|
||||||
|
"framer-motion": "^12.34.3",
|
||||||
|
"input-otp": "^1.4.2",
|
||||||
|
"lucide-react": "^0.562.0",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
|
"react": "^19.2.0",
|
||||||
|
"react-day-picker": "^9.13.0",
|
||||||
|
"react-dom": "^19.2.0",
|
||||||
|
"react-hook-form": "^7.70.0",
|
||||||
|
"react-resizable-panels": "^4.2.2",
|
||||||
|
"recharts": "^2.15.4",
|
||||||
|
"sonner": "^2.0.7",
|
||||||
|
"tailwind-merge": "^3.4.0",
|
||||||
|
"vaul": "^1.1.2",
|
||||||
|
"zod": "^4.3.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.39.1",
|
||||||
|
"@types/node": "^24.10.1",
|
||||||
|
"@types/react": "^19.2.5",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@vitejs/plugin-react": "^5.1.1",
|
||||||
|
"autoprefixer": "^10.4.23",
|
||||||
|
"eslint": "^9.39.1",
|
||||||
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.24",
|
||||||
|
"globals": "^16.5.0",
|
||||||
|
"kimi-plugin-inspect-react": "^1.0.3",
|
||||||
|
"postcss": "^8.5.6",
|
||||||
|
"tailwindcss": "^3.4.19",
|
||||||
|
"tailwindcss-animate": "^1.0.7",
|
||||||
|
"tw-animate-css": "^1.4.0",
|
||||||
|
"typescript": "~5.9.3",
|
||||||
|
"typescript-eslint": "^8.46.4",
|
||||||
|
"vite": "^7.2.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
@ -0,0 +1,102 @@
|
|||||||
|
/* App-specific styles */
|
||||||
|
|
||||||
|
/* Hide scrollbar for momentum cards */
|
||||||
|
.scrollbar-hide::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-hide {
|
||||||
|
-ms-overflow-style: none;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Smooth scroll behavior */
|
||||||
|
html {
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Selection color */
|
||||||
|
::selection {
|
||||||
|
background-color: rgba(255, 107, 53, 0.3);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Focus styles */
|
||||||
|
*:focus-visible {
|
||||||
|
outline: 2px solid #ff6b35;
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Button hover effects */
|
||||||
|
button {
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
transform: scale(0.98);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Card hover lift effect */
|
||||||
|
.stock-card {
|
||||||
|
transition: all 0.2s cubic-bezier(0.165, 0.84, 0.44, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Table row animations */
|
||||||
|
tr {
|
||||||
|
transition: background-color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Number formatting */
|
||||||
|
.number-font {
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-feature-settings: "tnum";
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Gradient backgrounds */
|
||||||
|
.gradient-bg {
|
||||||
|
background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Glass morphism effect */
|
||||||
|
.glass-effect {
|
||||||
|
background: rgba(26, 26, 26, 0.8);
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
-webkit-backdrop-filter: blur(12px);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Pulse animation for live data */
|
||||||
|
@keyframes pulse-live {
|
||||||
|
0%, 100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-indicator {
|
||||||
|
animation: pulse-live 2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Chart tooltip customization */
|
||||||
|
.recharts-tooltip-wrapper {
|
||||||
|
z-index: 1000 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Responsive adjustments */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.section-title {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-card {
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Print styles */
|
||||||
|
@media print {
|
||||||
|
.no-print {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,67 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Navbar } from '@/components/Navbar';
|
||||||
|
import { Footer } from '@/components/Footer';
|
||||||
|
import { StockDetailModal } from '@/components/StockDetailModal';
|
||||||
|
import { SectorDetailModal } from '@/components/SectorDetailModal';
|
||||||
|
import { MarketOverview } from '@/sections/MarketOverview';
|
||||||
|
import { MomentumSectors } from '@/sections/MomentumSectors';
|
||||||
|
import { HighLowStocks } from '@/sections/HighLowStocks';
|
||||||
|
import { PriceDistribution } from '@/sections/PriceDistribution';
|
||||||
|
import { MomentumRecommendation } from '@/sections/MomentumRecommendation';
|
||||||
|
import type { Sector } from '@/types';
|
||||||
|
import './App.css';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [selectedStock, setSelectedStock] = useState<string | null>(null);
|
||||||
|
const [isStockModalOpen, setIsStockModalOpen] = useState(false);
|
||||||
|
const [selectedSector, setSelectedSector] = useState<Sector | null>(null);
|
||||||
|
const [isSectorModalOpen, setIsSectorModalOpen] = useState(false);
|
||||||
|
|
||||||
|
// 处理导航栏搜索选择的版块
|
||||||
|
const handleSectorSelect = (sector: Sector) => {
|
||||||
|
setSelectedSector(sector);
|
||||||
|
setIsSectorModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 处理导航栏搜索选择的个股
|
||||||
|
const handleStockSelect = (stockCode: string) => {
|
||||||
|
setSelectedStock(stockCode);
|
||||||
|
setIsStockModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#0a0a0a]">
|
||||||
|
<Navbar
|
||||||
|
onSectorClick={handleSectorSelect}
|
||||||
|
onStockClick={handleStockSelect}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<main className="pb-8">
|
||||||
|
<MarketOverview />
|
||||||
|
<MomentumSectors />
|
||||||
|
<HighLowStocks />
|
||||||
|
<PriceDistribution />
|
||||||
|
<MomentumRecommendation />
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<Footer />
|
||||||
|
|
||||||
|
{/* Stock Detail Modal */}
|
||||||
|
<StockDetailModal
|
||||||
|
stockCode={selectedStock}
|
||||||
|
isOpen={isStockModalOpen}
|
||||||
|
onClose={() => setIsStockModalOpen(false)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Sector Detail Modal */}
|
||||||
|
<SectorDetailModal
|
||||||
|
sector={selectedSector}
|
||||||
|
isOpen={isSectorModalOpen}
|
||||||
|
onClose={() => setIsSectorModalOpen(false)}
|
||||||
|
onStockClick={handleStockSelect}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
||||||
@ -0,0 +1,259 @@
|
|||||||
|
import { useState, useEffect, useRef } from 'react';
|
||||||
|
import { TrendingUp, Search, Clock, X, Building2, TrendingUp as TrendingUpIcon } from 'lucide-react';
|
||||||
|
import { motion, AnimatePresence } from 'framer-motion';
|
||||||
|
import { stockDataService } from '@/services/stockData';
|
||||||
|
import type { Sector, Stock } from '@/types';
|
||||||
|
|
||||||
|
interface NavbarProps {
|
||||||
|
onSectorClick?: (sector: Sector) => void;
|
||||||
|
onStockClick?: (stockCode: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Navbar({ onSectorClick, onStockClick }: NavbarProps) {
|
||||||
|
const [scrolled, setScrolled] = useState(false);
|
||||||
|
const [currentTime, setCurrentTime] = useState(new Date());
|
||||||
|
const [searchOpen, setSearchOpen] = useState(false);
|
||||||
|
const [searchKeyword, setSearchKeyword] = useState('');
|
||||||
|
const [searchResults, setSearchResults] = useState<{ sectors: Sector[]; stocks: Stock[] }>({ sectors: [], stocks: [] });
|
||||||
|
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const searchContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleScroll = () => {
|
||||||
|
setScrolled(window.scrollY > 20);
|
||||||
|
};
|
||||||
|
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
setCurrentTime(new Date());
|
||||||
|
}, 1000);
|
||||||
|
|
||||||
|
window.addEventListener('scroll', handleScroll);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('scroll', handleScroll);
|
||||||
|
clearInterval(timer);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 点击外部关闭搜索
|
||||||
|
useEffect(() => {
|
||||||
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
|
if (searchContainerRef.current && !searchContainerRef.current.contains(e.target as Node)) {
|
||||||
|
setSearchOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
|
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 搜索逻辑
|
||||||
|
useEffect(() => {
|
||||||
|
if (searchKeyword.trim().length >= 1) {
|
||||||
|
const sectors = stockDataService.searchSectors(searchKeyword);
|
||||||
|
const stocks = stockDataService.searchStocks(searchKeyword);
|
||||||
|
setSearchResults({ sectors, stocks });
|
||||||
|
} else {
|
||||||
|
setSearchResults({ sectors: [], stocks: [] });
|
||||||
|
}
|
||||||
|
}, [searchKeyword]);
|
||||||
|
|
||||||
|
// 打开搜索时聚焦输入框
|
||||||
|
useEffect(() => {
|
||||||
|
if (searchOpen && searchInputRef.current) {
|
||||||
|
searchInputRef.current.focus();
|
||||||
|
}
|
||||||
|
}, [searchOpen]);
|
||||||
|
|
||||||
|
const handleSectorSelect = (sector: Sector) => {
|
||||||
|
setSearchOpen(false);
|
||||||
|
setSearchKeyword('');
|
||||||
|
onSectorClick?.(sector);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStockSelect = (stock: Stock) => {
|
||||||
|
setSearchOpen(false);
|
||||||
|
setSearchKeyword('');
|
||||||
|
onStockClick?.(stock.code);
|
||||||
|
};
|
||||||
|
|
||||||
|
const navItems = [
|
||||||
|
{ label: '首页', href: '#overview' },
|
||||||
|
{ label: '动量分析', href: '#momentum' },
|
||||||
|
{ label: '新高新低', href: '#highlow' },
|
||||||
|
{ label: '涨跌分布', href: '#distribution' },
|
||||||
|
{ label: '动量推荐', href: '#recommendation' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const hasResults = searchResults.sectors.length > 0 || searchResults.stocks.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<motion.nav
|
||||||
|
initial={{ y: -100 }}
|
||||||
|
animate={{ y: 0 }}
|
||||||
|
transition={{ duration: 0.5, ease: [0.165, 0.84, 0.44, 1] }}
|
||||||
|
className={`fixed top-0 left-0 right-0 z-50 h-16 transition-all duration-300 ${
|
||||||
|
scrolled ? 'glass border-b border-[#2a2a2a]' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="max-w-7xl mx-auto px-4 h-full flex items-center justify-between">
|
||||||
|
{/* Logo */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 bg-gradient-to-br from-[#ff6b35] to-[#ff9f43] rounded-lg flex items-center justify-center">
|
||||||
|
<TrendingUp className="w-6 h-6 text-white" />
|
||||||
|
</div>
|
||||||
|
<span className="text-xl font-bold text-white">A股智投</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Navigation */}
|
||||||
|
<div className="hidden md:flex items-center gap-1">
|
||||||
|
{navItems.map((item) => (
|
||||||
|
<a
|
||||||
|
key={item.label}
|
||||||
|
href={item.href}
|
||||||
|
className="px-4 py-2 text-sm text-[#b0b0b0] hover:text-[#ff6b35] transition-colors rounded-lg hover:bg-[#1a1a1a]"
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right Section */}
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
{/* Search */}
|
||||||
|
<div className="relative" ref={searchContainerRef}>
|
||||||
|
<AnimatePresence>
|
||||||
|
{searchOpen ? (
|
||||||
|
<motion.div
|
||||||
|
initial={{ width: 40, opacity: 0 }}
|
||||||
|
animate={{ width: 320, opacity: 1 }}
|
||||||
|
exit={{ width: 40, opacity: 0 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
className="relative"
|
||||||
|
>
|
||||||
|
<div className="flex items-center bg-[#1a1a1a] border border-[#2a2a2a] rounded-lg overflow-hidden">
|
||||||
|
<Search className="w-5 h-5 text-[#b0b0b0] ml-3" />
|
||||||
|
<input
|
||||||
|
ref={searchInputRef}
|
||||||
|
type="text"
|
||||||
|
value={searchKeyword}
|
||||||
|
onChange={(e) => setSearchKeyword(e.target.value)}
|
||||||
|
placeholder="搜索版块或个股..."
|
||||||
|
className="flex-1 bg-transparent px-3 py-2 text-sm text-white placeholder-[#666] outline-none"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setSearchOpen(false);
|
||||||
|
setSearchKeyword('');
|
||||||
|
}}
|
||||||
|
className="p-2 hover:bg-[#2a2a2a] transition-colors"
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4 text-[#b0b0b0]" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Search Results Dropdown */}
|
||||||
|
<AnimatePresence>
|
||||||
|
{hasResults && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: -10 }}
|
||||||
|
className="absolute top-full left-0 right-0 mt-2 bg-[#1a1a1a] border border-[#2a2a2a] rounded-xl shadow-2xl overflow-hidden max-h-80 overflow-y-auto"
|
||||||
|
>
|
||||||
|
{/* Sectors */}
|
||||||
|
{searchResults.sectors.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<div className="px-4 py-2 bg-[#0a0a0a] text-xs text-[#b0b0b0] flex items-center gap-2">
|
||||||
|
<Building2 className="w-3 h-3" />
|
||||||
|
版块 ({searchResults.sectors.length})
|
||||||
|
</div>
|
||||||
|
{searchResults.sectors.map((sector) => (
|
||||||
|
<button
|
||||||
|
key={sector.code}
|
||||||
|
onClick={() => handleSectorSelect(sector)}
|
||||||
|
className="w-full px-4 py-3 flex items-center justify-between hover:bg-[#2a2a2a] transition-colors text-left"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div className="text-white font-medium">{sector.name}</div>
|
||||||
|
<div className="text-xs text-[#b0b0b0]">排名 #{sector.rank} · 动量 {sector.momentumScore?.toFixed(0)}</div>
|
||||||
|
</div>
|
||||||
|
<div className={`text-sm font-medium number-font ${
|
||||||
|
sector.changePercent >= 0 ? 'text-[#ff3b30]' : 'text-[#00c853]'
|
||||||
|
}`}>
|
||||||
|
{sector.changePercent >= 0 ? '+' : ''}{sector.changePercent.toFixed(2)}%
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Stocks */}
|
||||||
|
{searchResults.stocks.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<div className="px-4 py-2 bg-[#0a0a0a] text-xs text-[#b0b0b0] flex items-center gap-2">
|
||||||
|
<TrendingUpIcon className="w-3 h-3" />
|
||||||
|
个股 ({searchResults.stocks.length})
|
||||||
|
</div>
|
||||||
|
{searchResults.stocks.map((stock) => (
|
||||||
|
<button
|
||||||
|
key={stock.code}
|
||||||
|
onClick={() => handleStockSelect(stock)}
|
||||||
|
className="w-full px-4 py-3 flex items-center justify-between hover:bg-[#2a2a2a] transition-colors text-left"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div className="text-white font-medium">{stock.name}</div>
|
||||||
|
<div className="text-xs text-[#b0b0b0]">{stock.code} · {stock.industry}</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<div className="text-white number-font">{stock.price.toFixed(2)}</div>
|
||||||
|
<div className={`text-xs number-font ${
|
||||||
|
stock.changePercent >= 0 ? 'text-[#ff3b30]' : 'text-[#00c853]'
|
||||||
|
}`}>
|
||||||
|
{stock.changePercent >= 0 ? '+' : ''}{stock.changePercent.toFixed(2)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* No Results */}
|
||||||
|
{searchKeyword.trim().length >= 1 && !hasResults && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: -10 }}
|
||||||
|
className="absolute top-full left-0 right-0 mt-2 bg-[#1a1a1a] border border-[#2a2a2a] rounded-xl shadow-2xl p-4 text-center"
|
||||||
|
>
|
||||||
|
<div className="text-[#b0b0b0] text-sm">未找到相关结果</div>
|
||||||
|
<div className="text-xs text-[#666] mt-1">试试搜索 "半导体" 或 "茅台"</div>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
</motion.div>
|
||||||
|
) : (
|
||||||
|
<motion.button
|
||||||
|
initial={{ scale: 0.8, opacity: 0 }}
|
||||||
|
animate={{ scale: 1, opacity: 1 }}
|
||||||
|
onClick={() => setSearchOpen(true)}
|
||||||
|
className="p-2 hover:bg-[#1a1a1a] rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
<Search className="w-5 h-5 text-[#b0b0b0]" />
|
||||||
|
</motion.button>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Time */}
|
||||||
|
<div className="hidden sm:flex items-center gap-2 text-sm text-[#b0b0b0]">
|
||||||
|
<Clock className="w-4 h-4" />
|
||||||
|
<span className="number-font">
|
||||||
|
{currentTime.toLocaleTimeString('zh-CN', { hour12: false })}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</motion.nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -0,0 +1,357 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { motion, AnimatePresence } from 'framer-motion';
|
||||||
|
import { X, BarChart3, Trophy, Target } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
XAxis, YAxis, Tooltip, ResponsiveContainer,
|
||||||
|
ComposedChart, Bar, Line
|
||||||
|
} from 'recharts';
|
||||||
|
import { CandlestickChart } from './CandlestickChart';
|
||||||
|
import { stockDataService } from '@/services/stockData';
|
||||||
|
import type { Sector, MomentumStock, KLineData, SectorMomentumHistory } from '@/types';
|
||||||
|
|
||||||
|
interface SectorDetailModalProps {
|
||||||
|
sector: Sector | null;
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onStockClick?: (stockCode: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const RankTooltip = ({ active, payload, label }: any) => {
|
||||||
|
if (active && payload && payload.length) {
|
||||||
|
return (
|
||||||
|
<div className="bg-[#1a1a1a] border border-[#2a2a2a] rounded-lg p-3 shadow-xl">
|
||||||
|
<p className="text-[#b0b0b0] text-xs mb-1">{label}</p>
|
||||||
|
<p className="text-white font-medium">排名: <span className="number-font text-[#ff6b35]">{payload[0].value}</span></p>
|
||||||
|
<p className="text-white font-medium">动量分: <span className="number-font text-[#ff9f43]">{payload[1]?.value}</span></p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function SectorDetailModal({ sector, isOpen, onClose, onStockClick }: SectorDetailModalProps) {
|
||||||
|
const [activeTab, setActiveTab] = useState<'overview' | 'stocks' | 'kline'>('overview');
|
||||||
|
const [rankHistory, setRankHistory] = useState<SectorMomentumHistory[]>([]);
|
||||||
|
const [momentumStocks, setMomentumStocks] = useState<MomentumStock[]>([]);
|
||||||
|
const [klineData, setKlineData] = useState<KLineData[]>([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (sector && isOpen) {
|
||||||
|
setRankHistory(stockDataService.getSectorRankHistory(sector.name));
|
||||||
|
setMomentumStocks(stockDataService.getSectorMomentumStocks(sector.name));
|
||||||
|
setKlineData(stockDataService.getSectorKLineData(sector.name, 60));
|
||||||
|
}
|
||||||
|
}, [sector, isOpen]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleEsc = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', handleEsc);
|
||||||
|
return () => window.removeEventListener('keydown', handleEsc);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
if (!sector) return null;
|
||||||
|
|
||||||
|
const getScoreColor = (score: number) => {
|
||||||
|
if (score >= 85) return 'text-[#ff3b30]';
|
||||||
|
if (score >= 70) return 'text-[#ff9f43]';
|
||||||
|
return 'text-[#b0b0b0]';
|
||||||
|
};
|
||||||
|
|
||||||
|
const getScoreBg = (score: number) => {
|
||||||
|
if (score >= 85) return 'bg-[#ff3b30]/20';
|
||||||
|
if (score >= 70) return 'bg-[#ff9f43]/20';
|
||||||
|
return 'bg-[#2a2a2a]';
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnimatePresence>
|
||||||
|
{isOpen && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, scale: 0.9, y: 20 }}
|
||||||
|
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, scale: 0.9, y: 20 }}
|
||||||
|
transition={{ duration: 0.3, ease: [0.165, 0.84, 0.44, 1] }}
|
||||||
|
className="bg-[#1a1a1a] border border-[#2a2a2a] rounded-2xl w-full max-w-5xl max-h-[90vh] overflow-hidden"
|
||||||
|
onClick={e => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between p-6 border-b border-[#2a2a2a]">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-2xl font-bold text-white">{sector.name}</h3>
|
||||||
|
<span className="text-sm text-[#b0b0b0]">版块代码: {sector.code}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className={`px-3 py-1 rounded-full text-sm font-medium ${
|
||||||
|
sector.changePercent >= 0 ? 'bg-[#ff3b30]/20 text-[#ff3b30]' : 'bg-[#00c853]/20 text-[#00c853]'
|
||||||
|
}`}>
|
||||||
|
{sector.changePercent >= 0 ? '+' : ''}{sector.changePercent.toFixed(2)}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="text-right">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm text-[#b0b0b0]">动量排名</span>
|
||||||
|
<span className="text-xl font-bold text-[#ff6b35] number-font">#{sector.rank}</span>
|
||||||
|
</div>
|
||||||
|
{sector.rankChange !== undefined && sector.rankChange !== 0 && (
|
||||||
|
<div className={`text-sm number-font ${sector.rankChange > 0 ? 'text-[#ff3b30]' : 'text-[#00c853]'}`}>
|
||||||
|
{sector.rankChange > 0 ? '↑' : '↓'} {Math.abs(sector.rankChange)} 位
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="p-2 hover:bg-[#2a2a2a] rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
<X className="w-5 h-5 text-[#b0b0b0]" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex border-b border-[#2a2a2a]">
|
||||||
|
{[
|
||||||
|
{ id: 'overview', label: '历史排名', icon: Trophy },
|
||||||
|
{ id: 'stocks', label: '动量个股', icon: Target },
|
||||||
|
{ id: 'kline', label: 'K线走势', icon: BarChart3 }
|
||||||
|
].map(tab => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => setActiveTab(tab.id as any)}
|
||||||
|
className={`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${
|
||||||
|
activeTab === tab.id
|
||||||
|
? 'text-[#ff6b35] border-b-2 border-[#ff6b35]'
|
||||||
|
: 'text-[#b0b0b0] hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<tab.icon className="w-4 h-4" />
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="p-6 overflow-y-auto max-h-[calc(90vh-180px)]">
|
||||||
|
{/* Overview Tab - Rank History */}
|
||||||
|
{activeTab === 'overview' && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Stats Cards */}
|
||||||
|
<div className="grid grid-cols-4 gap-4">
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">当前排名</div>
|
||||||
|
<div className="text-2xl font-bold text-[#ff6b35] number-font">#{sector.rank}</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">动量分数</div>
|
||||||
|
<div className={`text-2xl font-bold number-font ${getScoreColor(sector.momentumScore || 0)}`}>
|
||||||
|
{sector.momentumScore?.toFixed(1)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">排名变化</div>
|
||||||
|
<div className={`text-2xl font-bold number-font ${
|
||||||
|
(sector.rankChange || 0) > 0 ? 'text-[#ff3b30]' : (sector.rankChange || 0) < 0 ? 'text-[#00c853]' : 'text-[#b0b0b0]'
|
||||||
|
}`}>
|
||||||
|
{(sector.rankChange || 0) > 0 ? '+' : ''}{sector.rankChange}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">成交额</div>
|
||||||
|
<div className="text-2xl font-bold text-white number-font">
|
||||||
|
{(sector.turnover / 100000000).toFixed(1)}亿
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Rank History Chart */}
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4">
|
||||||
|
<h4 className="text-white font-medium mb-4">30日排名走势</h4>
|
||||||
|
<div className="h-64">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<ComposedChart data={rankHistory}>
|
||||||
|
<XAxis
|
||||||
|
dataKey="date"
|
||||||
|
tick={{ fill: '#b0b0b0', fontSize: 10 }}
|
||||||
|
axisLine={{ stroke: '#2a2a2a' }}
|
||||||
|
tickLine={false}
|
||||||
|
tickFormatter={(value) => value.slice(5)}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
yAxisId="rank"
|
||||||
|
orientation="left"
|
||||||
|
domain={[1, 20]}
|
||||||
|
reversed
|
||||||
|
tick={{ fill: '#b0b0b0', fontSize: 10 }}
|
||||||
|
axisLine={{ stroke: '#2a2a2a' }}
|
||||||
|
tickLine={false}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
yAxisId="score"
|
||||||
|
orientation="right"
|
||||||
|
domain={[0, 100]}
|
||||||
|
tick={{ fill: '#b0b0b0', fontSize: 10 }}
|
||||||
|
axisLine={{ stroke: '#2a2a2a' }}
|
||||||
|
tickLine={false}
|
||||||
|
/>
|
||||||
|
<Tooltip content={<RankTooltip />} />
|
||||||
|
<Bar
|
||||||
|
yAxisId="score"
|
||||||
|
dataKey="momentumScore"
|
||||||
|
fill="rgba(255, 159, 67, 0.3)"
|
||||||
|
radius={[2, 2, 0, 0]}
|
||||||
|
/>
|
||||||
|
<Line
|
||||||
|
yAxisId="rank"
|
||||||
|
type="monotone"
|
||||||
|
dataKey="rank"
|
||||||
|
stroke="#ff6b35"
|
||||||
|
strokeWidth={2}
|
||||||
|
dot={{ fill: '#ff6b35', strokeWidth: 0, r: 3 }}
|
||||||
|
/>
|
||||||
|
</ComposedChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Stocks Tab - Momentum Stocks */}
|
||||||
|
{activeTab === 'stocks' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h4 className="text-white font-medium">版块内动量个股排行</h4>
|
||||||
|
<span className="text-sm text-[#b0b0b0]">共 {momentumStocks.length} 只</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
{momentumStocks.map((stock, index) => (
|
||||||
|
<motion.div
|
||||||
|
key={stock.code}
|
||||||
|
initial={{ opacity: 0, y: 10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: index * 0.05 }}
|
||||||
|
whileHover={{ borderColor: 'rgba(255, 107, 53, 0.5)' }}
|
||||||
|
onClick={() => onStockClick?.(stock.code)}
|
||||||
|
className="bg-[#0a0a0a] border border-[#2a2a2a] rounded-xl p-4 cursor-pointer transition-all"
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className={`w-8 h-8 ${getScoreBg(stock.momentumScore)} rounded-lg flex items-center justify-center text-sm font-bold ${getScoreColor(stock.momentumScore)}`}>
|
||||||
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<div className="text-white font-medium">{stock.name}</div>
|
||||||
|
<div className="text-xs text-[#b0b0b0] number-font">{stock.code}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<div className="text-white font-bold number-font">{stock.price.toFixed(2)}</div>
|
||||||
|
<div className={`text-sm number-font ${stock.changePercent >= 0 ? 'stock-up' : 'stock-down'}`}>
|
||||||
|
{stock.changePercent >= 0 ? '+' : ''}{stock.changePercent.toFixed(2)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between mt-3 pt-3 border-t border-[#2a2a2a]">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-[#b0b0b0]">动量分</span>
|
||||||
|
<span className={`text-sm font-bold number-font ${getScoreColor(stock.momentumScore)}`}>
|
||||||
|
{stock.momentumScore}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-[#b0b0b0]">量比</span>
|
||||||
|
<span className="text-sm text-white number-font">{stock.volumeRatio.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
{stock.tags.map((tag, i) => (
|
||||||
|
<span key={i} className="text-xs bg-[#ff6b35]/20 text-[#ff6b35] px-2 py-0.5 rounded">
|
||||||
|
{tag}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
{stock.breakThrough && (
|
||||||
|
<span className="text-xs bg-[#ff3b30]/20 text-[#ff3b30] px-2 py-0.5 rounded">
|
||||||
|
突破
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* KLine Tab */}
|
||||||
|
{activeTab === 'kline' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h4 className="text-white font-medium">版块指数K线走势</h4>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Candlestick Chart with MA and Volume */}
|
||||||
|
<CandlestickChart
|
||||||
|
data={klineData}
|
||||||
|
height={420}
|
||||||
|
showVolume={true}
|
||||||
|
showMaSettings={true}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Stats */}
|
||||||
|
{klineData.length > 0 && (
|
||||||
|
<div className="grid grid-cols-5 gap-4">
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4 text-center">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">最新</div>
|
||||||
|
<div className="text-white font-bold number-font">{klineData[klineData.length - 1].close.toFixed(2)}</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4 text-center">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">最高</div>
|
||||||
|
<div className="text-[#ff3b30] font-bold number-font">
|
||||||
|
{Math.max(...klineData.map(d => d.high)).toFixed(2)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4 text-center">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">最低</div>
|
||||||
|
<div className="text-[#00c853] font-bold number-font">
|
||||||
|
{Math.min(...klineData.map(d => d.low)).toFixed(2)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4 text-center">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">涨跌</div>
|
||||||
|
<div className={`font-bold number-font ${
|
||||||
|
klineData[klineData.length - 1].close >= klineData[0].open ? 'text-[#ff3b30]' : 'text-[#00c853]'
|
||||||
|
}`}>
|
||||||
|
{((klineData[klineData.length - 1].close - klineData[0].open) / klineData[0].open * 100).toFixed(2)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-[#0a0a0a] rounded-xl p-4 text-center">
|
||||||
|
<div className="text-xs text-[#b0b0b0] mb-1">振幅</div>
|
||||||
|
<div className="text-white font-bold number-font">
|
||||||
|
{((Math.max(...klineData.map(d => d.high)) - Math.min(...klineData.map(d => d.low))) / klineData[0].open * 100).toFixed(2)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -0,0 +1,64 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||||
|
import { ChevronDownIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Accordion({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||||
|
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionItem({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Item
|
||||||
|
data-slot="accordion-item"
|
||||||
|
className={cn("border-b last:border-b-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionTrigger({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Header className="flex">
|
||||||
|
<AccordionPrimitive.Trigger
|
||||||
|
data-slot="accordion-trigger"
|
||||||
|
className={cn(
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||||
|
</AccordionPrimitive.Trigger>
|
||||||
|
</AccordionPrimitive.Header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Content
|
||||||
|
data-slot="accordion-content"
|
||||||
|
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||||
|
</AccordionPrimitive.Content>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||||
@ -0,0 +1,155 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { buttonVariants } from "@/components/ui/button"
|
||||||
|
|
||||||
|
function AlertDialog({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||||
|
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Overlay
|
||||||
|
data-slot="alert-dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPortal>
|
||||||
|
<AlertDialogOverlay />
|
||||||
|
<AlertDialogPrimitive.Content
|
||||||
|
data-slot="alert-dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</AlertDialogPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogHeader({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogFooter({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogTitle({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Title
|
||||||
|
data-slot="alert-dialog-title"
|
||||||
|
className={cn("text-lg font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Description
|
||||||
|
data-slot="alert-dialog-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogAction({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Action
|
||||||
|
className={cn(buttonVariants(), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogCancel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Cancel
|
||||||
|
className={cn(buttonVariants({ variant: "outline" }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogPortal,
|
||||||
|
AlertDialogOverlay,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
}
|
||||||
@ -0,0 +1,66 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const alertVariants = cva(
|
||||||
|
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-card text-card-foreground",
|
||||||
|
destructive:
|
||||||
|
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Alert({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert"
|
||||||
|
role="alert"
|
||||||
|
className={cn(alertVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-title"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Alert, AlertTitle, AlertDescription }
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
|
||||||
|
|
||||||
|
function AspectRatio({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
||||||
|
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
export { AspectRatio }
|
||||||
@ -0,0 +1,51 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Avatar({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Root
|
||||||
|
data-slot="avatar"
|
||||||
|
className={cn(
|
||||||
|
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarImage({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Image
|
||||||
|
data-slot="avatar-image"
|
||||||
|
className={cn("aspect-square size-full", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarFallback({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Fallback
|
||||||
|
data-slot="avatar-fallback"
|
||||||
|
className={cn(
|
||||||
|
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Avatar, AvatarImage, AvatarFallback }
|
||||||
@ -0,0 +1,46 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
|
secondary:
|
||||||
|
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
|
destructive:
|
||||||
|
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Badge({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span"> &
|
||||||
|
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot : "span"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="badge"
|
||||||
|
className={cn(badgeVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants }
|
||||||
@ -0,0 +1,109 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||||
|
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||||
|
return (
|
||||||
|
<ol
|
||||||
|
data-slot="breadcrumb-list"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
data-slot="breadcrumb-item"
|
||||||
|
className={cn("inline-flex items-center gap-1.5", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbLink({
|
||||||
|
asChild,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"a"> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "a"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="breadcrumb-link"
|
||||||
|
className={cn("hover:text-foreground transition-colors", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="breadcrumb-page"
|
||||||
|
role="link"
|
||||||
|
aria-disabled="true"
|
||||||
|
aria-current="page"
|
||||||
|
className={cn("text-foreground font-normal", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbSeparator({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"li">) {
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
data-slot="breadcrumb-separator"
|
||||||
|
role="presentation"
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn("[&>svg]:size-3.5", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children ?? <ChevronRight />}
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbEllipsis({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="breadcrumb-ellipsis"
|
||||||
|
role="presentation"
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn("flex size-9 items-center justify-center", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<MoreHorizontal className="size-4" />
|
||||||
|
<span className="sr-only">More</span>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Breadcrumb,
|
||||||
|
BreadcrumbList,
|
||||||
|
BreadcrumbItem,
|
||||||
|
BreadcrumbLink,
|
||||||
|
BreadcrumbPage,
|
||||||
|
BreadcrumbSeparator,
|
||||||
|
BreadcrumbEllipsis,
|
||||||
|
}
|
||||||
@ -0,0 +1,83 @@
|
|||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
const buttonGroupVariants = cva(
|
||||||
|
"flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
orientation: {
|
||||||
|
horizontal:
|
||||||
|
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
|
||||||
|
vertical:
|
||||||
|
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
orientation: "horizontal",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function ButtonGroup({
|
||||||
|
className,
|
||||||
|
orientation,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
data-slot="button-group"
|
||||||
|
data-orientation={orientation}
|
||||||
|
className={cn(buttonGroupVariants({ orientation }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ButtonGroupText({
|
||||||
|
className,
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "div"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
className={cn(
|
||||||
|
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ButtonGroupSeparator({
|
||||||
|
className,
|
||||||
|
orientation = "vertical",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Separator>) {
|
||||||
|
return (
|
||||||
|
<Separator
|
||||||
|
data-slot="button-group-separator"
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
ButtonGroup,
|
||||||
|
ButtonGroupSeparator,
|
||||||
|
ButtonGroupText,
|
||||||
|
buttonGroupVariants,
|
||||||
|
}
|
||||||
@ -0,0 +1,62 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
|
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||||
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
|
icon: "size-9",
|
||||||
|
"icon-sm": "size-8",
|
||||||
|
"icon-lg": "size-10",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Button({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"button"> &
|
||||||
|
VariantProps<typeof buttonVariants> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "button"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="button"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Button, buttonVariants }
|
||||||
@ -0,0 +1,220 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import {
|
||||||
|
ChevronDownIcon,
|
||||||
|
ChevronLeftIcon,
|
||||||
|
ChevronRightIcon,
|
||||||
|
} from "lucide-react"
|
||||||
|
import {
|
||||||
|
DayPicker,
|
||||||
|
getDefaultClassNames,
|
||||||
|
type DayButton,
|
||||||
|
} from "react-day-picker"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button, buttonVariants } from "@/components/ui/button"
|
||||||
|
|
||||||
|
function Calendar({
|
||||||
|
className,
|
||||||
|
classNames,
|
||||||
|
showOutsideDays = true,
|
||||||
|
captionLayout = "label",
|
||||||
|
buttonVariant = "ghost",
|
||||||
|
formatters,
|
||||||
|
components,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayPicker> & {
|
||||||
|
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||||
|
}) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DayPicker
|
||||||
|
showOutsideDays={showOutsideDays}
|
||||||
|
className={cn(
|
||||||
|
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||||
|
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||||
|
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
captionLayout={captionLayout}
|
||||||
|
formatters={{
|
||||||
|
formatMonthDropdown: (date) =>
|
||||||
|
date.toLocaleString("default", { month: "short" }),
|
||||||
|
...formatters,
|
||||||
|
}}
|
||||||
|
classNames={{
|
||||||
|
root: cn("w-fit", defaultClassNames.root),
|
||||||
|
months: cn(
|
||||||
|
"flex gap-4 flex-col md:flex-row relative",
|
||||||
|
defaultClassNames.months
|
||||||
|
),
|
||||||
|
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||||
|
nav: cn(
|
||||||
|
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||||
|
defaultClassNames.nav
|
||||||
|
),
|
||||||
|
button_previous: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||||
|
defaultClassNames.button_previous
|
||||||
|
),
|
||||||
|
button_next: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||||
|
defaultClassNames.button_next
|
||||||
|
),
|
||||||
|
month_caption: cn(
|
||||||
|
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||||
|
defaultClassNames.month_caption
|
||||||
|
),
|
||||||
|
dropdowns: cn(
|
||||||
|
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||||
|
defaultClassNames.dropdowns
|
||||||
|
),
|
||||||
|
dropdown_root: cn(
|
||||||
|
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||||
|
defaultClassNames.dropdown_root
|
||||||
|
),
|
||||||
|
dropdown: cn(
|
||||||
|
"absolute bg-popover inset-0 opacity-0",
|
||||||
|
defaultClassNames.dropdown
|
||||||
|
),
|
||||||
|
caption_label: cn(
|
||||||
|
"select-none font-medium",
|
||||||
|
captionLayout === "label"
|
||||||
|
? "text-sm"
|
||||||
|
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||||
|
defaultClassNames.caption_label
|
||||||
|
),
|
||||||
|
table: "w-full border-collapse",
|
||||||
|
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||||
|
weekday: cn(
|
||||||
|
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
|
||||||
|
defaultClassNames.weekday
|
||||||
|
),
|
||||||
|
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||||
|
week_number_header: cn(
|
||||||
|
"select-none w-(--cell-size)",
|
||||||
|
defaultClassNames.week_number_header
|
||||||
|
),
|
||||||
|
week_number: cn(
|
||||||
|
"text-[0.8rem] select-none text-muted-foreground",
|
||||||
|
defaultClassNames.week_number
|
||||||
|
),
|
||||||
|
day: cn(
|
||||||
|
"relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||||
|
props.showWeekNumber
|
||||||
|
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
|
||||||
|
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
|
||||||
|
defaultClassNames.day
|
||||||
|
),
|
||||||
|
range_start: cn(
|
||||||
|
"rounded-l-md bg-accent",
|
||||||
|
defaultClassNames.range_start
|
||||||
|
),
|
||||||
|
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||||
|
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||||
|
today: cn(
|
||||||
|
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||||
|
defaultClassNames.today
|
||||||
|
),
|
||||||
|
outside: cn(
|
||||||
|
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||||
|
defaultClassNames.outside
|
||||||
|
),
|
||||||
|
disabled: cn(
|
||||||
|
"text-muted-foreground opacity-50",
|
||||||
|
defaultClassNames.disabled
|
||||||
|
),
|
||||||
|
hidden: cn("invisible", defaultClassNames.hidden),
|
||||||
|
...classNames,
|
||||||
|
}}
|
||||||
|
components={{
|
||||||
|
Root: ({ className, rootRef, ...props }) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="calendar"
|
||||||
|
ref={rootRef}
|
||||||
|
className={cn(className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
Chevron: ({ className, orientation, ...props }) => {
|
||||||
|
if (orientation === "left") {
|
||||||
|
return (
|
||||||
|
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (orientation === "right") {
|
||||||
|
return (
|
||||||
|
<ChevronRightIcon
|
||||||
|
className={cn("size-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
},
|
||||||
|
DayButton: CalendarDayButton,
|
||||||
|
WeekNumber: ({ children, ...props }) => {
|
||||||
|
return (
|
||||||
|
<td {...props}>
|
||||||
|
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
...components,
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CalendarDayButton({
|
||||||
|
className,
|
||||||
|
day,
|
||||||
|
modifiers,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayButton>) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
const ref = React.useRef<HTMLButtonElement>(null)
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (modifiers.focused) ref.current?.focus()
|
||||||
|
}, [modifiers.focused])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
data-day={day.date.toLocaleDateString()}
|
||||||
|
data-selected-single={
|
||||||
|
modifiers.selected &&
|
||||||
|
!modifiers.range_start &&
|
||||||
|
!modifiers.range_end &&
|
||||||
|
!modifiers.range_middle
|
||||||
|
}
|
||||||
|
data-range-start={modifiers.range_start}
|
||||||
|
data-range-end={modifiers.range_end}
|
||||||
|
data-range-middle={modifiers.range_middle}
|
||||||
|
className={cn(
|
||||||
|
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||||
|
defaultClassNames.day,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Calendar, CalendarDayButton }
|
||||||
@ -0,0 +1,92 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card"
|
||||||
|
className={cn(
|
||||||
|
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-header"
|
||||||
|
className={cn(
|
||||||
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-title"
|
||||||
|
className={cn("leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-action"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-content"
|
||||||
|
className={cn("px-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-footer"
|
||||||
|
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Card,
|
||||||
|
CardHeader,
|
||||||
|
CardFooter,
|
||||||
|
CardTitle,
|
||||||
|
CardAction,
|
||||||
|
CardDescription,
|
||||||
|
CardContent,
|
||||||
|
}
|
||||||
@ -0,0 +1,239 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import useEmblaCarousel, {
|
||||||
|
type UseEmblaCarouselType,
|
||||||
|
} from "embla-carousel-react"
|
||||||
|
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
|
||||||
|
type CarouselApi = UseEmblaCarouselType[1]
|
||||||
|
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||||
|
type CarouselOptions = UseCarouselParameters[0]
|
||||||
|
type CarouselPlugin = UseCarouselParameters[1]
|
||||||
|
|
||||||
|
type CarouselProps = {
|
||||||
|
opts?: CarouselOptions
|
||||||
|
plugins?: CarouselPlugin
|
||||||
|
orientation?: "horizontal" | "vertical"
|
||||||
|
setApi?: (api: CarouselApi) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
type CarouselContextProps = {
|
||||||
|
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||||
|
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||||
|
scrollPrev: () => void
|
||||||
|
scrollNext: () => void
|
||||||
|
canScrollPrev: boolean
|
||||||
|
canScrollNext: boolean
|
||||||
|
} & CarouselProps
|
||||||
|
|
||||||
|
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||||
|
|
||||||
|
function useCarousel() {
|
||||||
|
const context = React.useContext(CarouselContext)
|
||||||
|
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useCarousel must be used within a <Carousel />")
|
||||||
|
}
|
||||||
|
|
||||||
|
return context
|
||||||
|
}
|
||||||
|
|
||||||
|
function Carousel({
|
||||||
|
orientation = "horizontal",
|
||||||
|
opts,
|
||||||
|
setApi,
|
||||||
|
plugins,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & CarouselProps) {
|
||||||
|
const [carouselRef, api] = useEmblaCarousel(
|
||||||
|
{
|
||||||
|
...opts,
|
||||||
|
axis: orientation === "horizontal" ? "x" : "y",
|
||||||
|
},
|
||||||
|
plugins
|
||||||
|
)
|
||||||
|
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||||
|
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||||
|
|
||||||
|
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||||
|
if (!api) return
|
||||||
|
setCanScrollPrev(api.canScrollPrev())
|
||||||
|
setCanScrollNext(api.canScrollNext())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const scrollPrev = React.useCallback(() => {
|
||||||
|
api?.scrollPrev()
|
||||||
|
}, [api])
|
||||||
|
|
||||||
|
const scrollNext = React.useCallback(() => {
|
||||||
|
api?.scrollNext()
|
||||||
|
}, [api])
|
||||||
|
|
||||||
|
const handleKeyDown = React.useCallback(
|
||||||
|
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||||
|
if (event.key === "ArrowLeft") {
|
||||||
|
event.preventDefault()
|
||||||
|
scrollPrev()
|
||||||
|
} else if (event.key === "ArrowRight") {
|
||||||
|
event.preventDefault()
|
||||||
|
scrollNext()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[scrollPrev, scrollNext]
|
||||||
|
)
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!api || !setApi) return
|
||||||
|
setApi(api)
|
||||||
|
}, [api, setApi])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!api) return
|
||||||
|
onSelect(api)
|
||||||
|
api.on("reInit", onSelect)
|
||||||
|
api.on("select", onSelect)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
api?.off("select", onSelect)
|
||||||
|
}
|
||||||
|
}, [api, onSelect])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CarouselContext.Provider
|
||||||
|
value={{
|
||||||
|
carouselRef,
|
||||||
|
api: api,
|
||||||
|
opts,
|
||||||
|
orientation:
|
||||||
|
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||||
|
scrollPrev,
|
||||||
|
scrollNext,
|
||||||
|
canScrollPrev,
|
||||||
|
canScrollNext,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onKeyDownCapture={handleKeyDown}
|
||||||
|
className={cn("relative", className)}
|
||||||
|
role="region"
|
||||||
|
aria-roledescription="carousel"
|
||||||
|
data-slot="carousel"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</CarouselContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
const { carouselRef, orientation } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={carouselRef}
|
||||||
|
className="overflow-hidden"
|
||||||
|
data-slot="carousel-content"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex",
|
||||||
|
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
const { orientation } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
aria-roledescription="slide"
|
||||||
|
data-slot="carousel-item"
|
||||||
|
className={cn(
|
||||||
|
"min-w-0 shrink-0 grow-0 basis-full",
|
||||||
|
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselPrevious({
|
||||||
|
className,
|
||||||
|
variant = "outline",
|
||||||
|
size = "icon",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Button>) {
|
||||||
|
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
data-slot="carousel-previous"
|
||||||
|
variant={variant}
|
||||||
|
size={size}
|
||||||
|
className={cn(
|
||||||
|
"absolute size-8 rounded-full",
|
||||||
|
orientation === "horizontal"
|
||||||
|
? "top-1/2 -left-12 -translate-y-1/2"
|
||||||
|
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
disabled={!canScrollPrev}
|
||||||
|
onClick={scrollPrev}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ArrowLeft />
|
||||||
|
<span className="sr-only">Previous slide</span>
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselNext({
|
||||||
|
className,
|
||||||
|
variant = "outline",
|
||||||
|
size = "icon",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Button>) {
|
||||||
|
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
data-slot="carousel-next"
|
||||||
|
variant={variant}
|
||||||
|
size={size}
|
||||||
|
className={cn(
|
||||||
|
"absolute size-8 rounded-full",
|
||||||
|
orientation === "horizontal"
|
||||||
|
? "top-1/2 -right-12 -translate-y-1/2"
|
||||||
|
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
disabled={!canScrollNext}
|
||||||
|
onClick={scrollNext}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ArrowRight />
|
||||||
|
<span className="sr-only">Next slide</span>
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
type CarouselApi,
|
||||||
|
Carousel,
|
||||||
|
CarouselContent,
|
||||||
|
CarouselItem,
|
||||||
|
CarouselPrevious,
|
||||||
|
CarouselNext,
|
||||||
|
}
|
||||||
@ -0,0 +1,357 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as RechartsPrimitive from "recharts"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||||
|
const THEMES = { light: "", dark: ".dark" } as const
|
||||||
|
|
||||||
|
export type ChartConfig = {
|
||||||
|
[k in string]: {
|
||||||
|
label?: React.ReactNode
|
||||||
|
icon?: React.ComponentType
|
||||||
|
} & (
|
||||||
|
| { color?: string; theme?: never }
|
||||||
|
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChartContextProps = {
|
||||||
|
config: ChartConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
||||||
|
|
||||||
|
function useChart() {
|
||||||
|
const context = React.useContext(ChartContext)
|
||||||
|
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useChart must be used within a <ChartContainer />")
|
||||||
|
}
|
||||||
|
|
||||||
|
return context
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartContainer({
|
||||||
|
id,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
config,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
config: ChartConfig
|
||||||
|
children: React.ComponentProps<
|
||||||
|
typeof RechartsPrimitive.ResponsiveContainer
|
||||||
|
>["children"]
|
||||||
|
}) {
|
||||||
|
const uniqueId = React.useId()
|
||||||
|
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChartContext.Provider value={{ config }}>
|
||||||
|
<div
|
||||||
|
data-slot="chart"
|
||||||
|
data-chart={chartId}
|
||||||
|
className={cn(
|
||||||
|
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChartStyle id={chartId} config={config} />
|
||||||
|
<RechartsPrimitive.ResponsiveContainer>
|
||||||
|
{children}
|
||||||
|
</RechartsPrimitive.ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</ChartContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||||
|
const colorConfig = Object.entries(config).filter(
|
||||||
|
([, config]) => config.theme || config.color
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!colorConfig.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<style
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: Object.entries(THEMES)
|
||||||
|
.map(
|
||||||
|
([theme, prefix]) => `
|
||||||
|
${prefix} [data-chart=${id}] {
|
||||||
|
${colorConfig
|
||||||
|
.map(([key, itemConfig]) => {
|
||||||
|
const color =
|
||||||
|
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
|
||||||
|
itemConfig.color
|
||||||
|
return color ? ` --color-${key}: ${color};` : null
|
||||||
|
})
|
||||||
|
.join("\n")}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
)
|
||||||
|
.join("\n"),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartTooltip = RechartsPrimitive.Tooltip
|
||||||
|
|
||||||
|
function ChartTooltipContent({
|
||||||
|
active,
|
||||||
|
payload,
|
||||||
|
className,
|
||||||
|
indicator = "dot",
|
||||||
|
hideLabel = false,
|
||||||
|
hideIndicator = false,
|
||||||
|
label,
|
||||||
|
labelFormatter,
|
||||||
|
labelClassName,
|
||||||
|
formatter,
|
||||||
|
color,
|
||||||
|
nameKey,
|
||||||
|
labelKey,
|
||||||
|
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
hideLabel?: boolean
|
||||||
|
hideIndicator?: boolean
|
||||||
|
indicator?: "line" | "dot" | "dashed"
|
||||||
|
nameKey?: string
|
||||||
|
labelKey?: string
|
||||||
|
}) {
|
||||||
|
const { config } = useChart()
|
||||||
|
|
||||||
|
const tooltipLabel = React.useMemo(() => {
|
||||||
|
if (hideLabel || !payload?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const [item] = payload
|
||||||
|
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
|
||||||
|
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||||
|
const value =
|
||||||
|
!labelKey && typeof label === "string"
|
||||||
|
? config[label as keyof typeof config]?.label || label
|
||||||
|
: itemConfig?.label
|
||||||
|
|
||||||
|
if (labelFormatter) {
|
||||||
|
return (
|
||||||
|
<div className={cn("font-medium", labelClassName)}>
|
||||||
|
{labelFormatter(value, payload)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className={cn("font-medium", labelClassName)}>{value}</div>
|
||||||
|
}, [
|
||||||
|
label,
|
||||||
|
labelFormatter,
|
||||||
|
payload,
|
||||||
|
hideLabel,
|
||||||
|
labelClassName,
|
||||||
|
config,
|
||||||
|
labelKey,
|
||||||
|
])
|
||||||
|
|
||||||
|
if (!active || !payload?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const nestLabel = payload.length === 1 && indicator !== "dot"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{!nestLabel ? tooltipLabel : null}
|
||||||
|
<div className="grid gap-1.5">
|
||||||
|
{payload
|
||||||
|
.filter((item) => item.type !== "none")
|
||||||
|
.map((item, index) => {
|
||||||
|
const key = `${nameKey || item.name || item.dataKey || "value"}`
|
||||||
|
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||||
|
const indicatorColor = color || item.payload.fill || item.color
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.dataKey}
|
||||||
|
className={cn(
|
||||||
|
"[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
|
||||||
|
indicator === "dot" && "items-center"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{formatter && item?.value !== undefined && item.name ? (
|
||||||
|
formatter(item.value, item.name, item, index, item.payload)
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{itemConfig?.icon ? (
|
||||||
|
<itemConfig.icon />
|
||||||
|
) : (
|
||||||
|
!hideIndicator && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
|
||||||
|
{
|
||||||
|
"h-2.5 w-2.5": indicator === "dot",
|
||||||
|
"w-1": indicator === "line",
|
||||||
|
"w-0 border-[1.5px] border-dashed bg-transparent":
|
||||||
|
indicator === "dashed",
|
||||||
|
"my-0.5": nestLabel && indicator === "dashed",
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--color-bg": indicatorColor,
|
||||||
|
"--color-border": indicatorColor,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-1 justify-between leading-none",
|
||||||
|
nestLabel ? "items-end" : "items-center"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="grid gap-1.5">
|
||||||
|
{nestLabel ? tooltipLabel : null}
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{itemConfig?.label || item.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{item.value && (
|
||||||
|
<span className="text-foreground font-mono font-medium tabular-nums">
|
||||||
|
{item.value.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartLegend = RechartsPrimitive.Legend
|
||||||
|
|
||||||
|
function ChartLegendContent({
|
||||||
|
className,
|
||||||
|
hideIcon = false,
|
||||||
|
payload,
|
||||||
|
verticalAlign = "bottom",
|
||||||
|
nameKey,
|
||||||
|
}: React.ComponentProps<"div"> &
|
||||||
|
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
|
||||||
|
hideIcon?: boolean
|
||||||
|
nameKey?: string
|
||||||
|
}) {
|
||||||
|
const { config } = useChart()
|
||||||
|
|
||||||
|
if (!payload?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-center gap-4",
|
||||||
|
verticalAlign === "top" ? "pb-3" : "pt-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{payload
|
||||||
|
.filter((item) => item.type !== "none")
|
||||||
|
.map((item) => {
|
||||||
|
const key = `${nameKey || item.dataKey || "value"}`
|
||||||
|
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.value}
|
||||||
|
className={cn(
|
||||||
|
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{itemConfig?.icon && !hideIcon ? (
|
||||||
|
<itemConfig.icon />
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||||
|
style={{
|
||||||
|
backgroundColor: item.color,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{itemConfig?.label}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to extract item config from a payload.
|
||||||
|
function getPayloadConfigFromPayload(
|
||||||
|
config: ChartConfig,
|
||||||
|
payload: unknown,
|
||||||
|
key: string
|
||||||
|
) {
|
||||||
|
if (typeof payload !== "object" || payload === null) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const payloadPayload =
|
||||||
|
"payload" in payload &&
|
||||||
|
typeof payload.payload === "object" &&
|
||||||
|
payload.payload !== null
|
||||||
|
? payload.payload
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
let configLabelKey: string = key
|
||||||
|
|
||||||
|
if (
|
||||||
|
key in payload &&
|
||||||
|
typeof payload[key as keyof typeof payload] === "string"
|
||||||
|
) {
|
||||||
|
configLabelKey = payload[key as keyof typeof payload] as string
|
||||||
|
} else if (
|
||||||
|
payloadPayload &&
|
||||||
|
key in payloadPayload &&
|
||||||
|
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
|
||||||
|
) {
|
||||||
|
configLabelKey = payloadPayload[
|
||||||
|
key as keyof typeof payloadPayload
|
||||||
|
] as string
|
||||||
|
}
|
||||||
|
|
||||||
|
return configLabelKey in config
|
||||||
|
? config[configLabelKey]
|
||||||
|
: config[key as keyof typeof config]
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
ChartContainer,
|
||||||
|
ChartTooltip,
|
||||||
|
ChartTooltipContent,
|
||||||
|
ChartLegend,
|
||||||
|
ChartLegendContent,
|
||||||
|
ChartStyle,
|
||||||
|
}
|
||||||
@ -0,0 +1,32 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||||
|
import { CheckIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Checkbox({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<CheckboxPrimitive.Root
|
||||||
|
data-slot="checkbox"
|
||||||
|
className={cn(
|
||||||
|
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<CheckboxPrimitive.Indicator
|
||||||
|
data-slot="checkbox-indicator"
|
||||||
|
className="grid place-content-center text-current transition-none"
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3.5" />
|
||||||
|
</CheckboxPrimitive.Indicator>
|
||||||
|
</CheckboxPrimitive.Root>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Checkbox }
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||||
|
|
||||||
|
function Collapsible({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||||
|
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function CollapsibleTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||||
|
return (
|
||||||
|
<CollapsiblePrimitive.CollapsibleTrigger
|
||||||
|
data-slot="collapsible-trigger"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CollapsibleContent({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||||
|
return (
|
||||||
|
<CollapsiblePrimitive.CollapsibleContent
|
||||||
|
data-slot="collapsible-content"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||||
@ -0,0 +1,182 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Command as CommandPrimitive } from "cmdk"
|
||||||
|
import { SearchIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog"
|
||||||
|
|
||||||
|
function Command({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive
|
||||||
|
data-slot="command"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandDialog({
|
||||||
|
title = "Command Palette",
|
||||||
|
description = "Search for a command to run...",
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Dialog> & {
|
||||||
|
title?: string
|
||||||
|
description?: string
|
||||||
|
className?: string
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Dialog {...props}>
|
||||||
|
<DialogHeader className="sr-only">
|
||||||
|
<DialogTitle>{title}</DialogTitle>
|
||||||
|
<DialogDescription>{description}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogContent
|
||||||
|
className={cn("overflow-hidden p-0", className)}
|
||||||
|
showCloseButton={showCloseButton}
|
||||||
|
>
|
||||||
|
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||||
|
{children}
|
||||||
|
</Command>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandInput({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="command-input-wrapper"
|
||||||
|
className="flex h-9 items-center gap-2 border-b px-3"
|
||||||
|
>
|
||||||
|
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||||
|
<CommandPrimitive.Input
|
||||||
|
data-slot="command-input"
|
||||||
|
className={cn(
|
||||||
|
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandList({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.List
|
||||||
|
data-slot="command-list"
|
||||||
|
className={cn(
|
||||||
|
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandEmpty({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Empty
|
||||||
|
data-slot="command-empty"
|
||||||
|
className="py-6 text-center text-sm"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandGroup({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Group
|
||||||
|
data-slot="command-group"
|
||||||
|
className={cn(
|
||||||
|
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Separator
|
||||||
|
data-slot="command-separator"
|
||||||
|
className={cn("bg-border -mx-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandItem({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Item
|
||||||
|
data-slot="command-item"
|
||||||
|
className={cn(
|
||||||
|
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="command-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Command,
|
||||||
|
CommandDialog,
|
||||||
|
CommandInput,
|
||||||
|
CommandList,
|
||||||
|
CommandEmpty,
|
||||||
|
CommandGroup,
|
||||||
|
CommandItem,
|
||||||
|
CommandShortcut,
|
||||||
|
CommandSeparator,
|
||||||
|
}
|
||||||
@ -0,0 +1,252 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function ContextMenu({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||||
|
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSub({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||||
|
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.RadioGroup
|
||||||
|
data-slot="context-menu-radio-group"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.SubTrigger
|
||||||
|
data-slot="context-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto" />
|
||||||
|
</ContextMenuPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.SubContent
|
||||||
|
data-slot="context-menu-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Portal>
|
||||||
|
<ContextMenuPrimitive.Content
|
||||||
|
data-slot="context-menu-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</ContextMenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Item
|
||||||
|
data-slot="context-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.CheckboxItem
|
||||||
|
data-slot="context-menu-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</ContextMenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.RadioItem
|
||||||
|
data-slot="context-menu-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</ContextMenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Label
|
||||||
|
data-slot="context-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Separator
|
||||||
|
data-slot="context-menu-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="context-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
ContextMenu,
|
||||||
|
ContextMenuTrigger,
|
||||||
|
ContextMenuContent,
|
||||||
|
ContextMenuItem,
|
||||||
|
ContextMenuCheckboxItem,
|
||||||
|
ContextMenuRadioItem,
|
||||||
|
ContextMenuLabel,
|
||||||
|
ContextMenuSeparator,
|
||||||
|
ContextMenuShortcut,
|
||||||
|
ContextMenuGroup,
|
||||||
|
ContextMenuPortal,
|
||||||
|
ContextMenuSub,
|
||||||
|
ContextMenuSubContent,
|
||||||
|
ContextMenuSubTrigger,
|
||||||
|
ContextMenuRadioGroup,
|
||||||
|
}
|
||||||
@ -0,0 +1,141 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||||
|
import { XIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Dialog({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||||
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||||
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||||
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogClose({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||||
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Overlay
|
||||||
|
data-slot="dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DialogPortal data-slot="dialog-portal">
|
||||||
|
<DialogOverlay />
|
||||||
|
<DialogPrimitive.Content
|
||||||
|
data-slot="dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close
|
||||||
|
data-slot="dialog-close"
|
||||||
|
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||||
|
>
|
||||||
|
<XIcon />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</DialogPrimitive.Content>
|
||||||
|
</DialogPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTitle({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Title
|
||||||
|
data-slot="dialog-title"
|
||||||
|
className={cn("text-lg leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Description
|
||||||
|
data-slot="dialog-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogOverlay,
|
||||||
|
DialogPortal,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
}
|
||||||
@ -0,0 +1,135 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Drawer as DrawerPrimitive } from "vaul"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Drawer({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||||
|
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||||
|
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||||
|
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerClose({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||||
|
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<DrawerPrimitive.Overlay
|
||||||
|
data-slot="drawer-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<DrawerPortal data-slot="drawer-portal">
|
||||||
|
<DrawerOverlay />
|
||||||
|
<DrawerPrimitive.Content
|
||||||
|
data-slot="drawer-content"
|
||||||
|
className={cn(
|
||||||
|
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
|
||||||
|
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
||||||
|
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
||||||
|
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||||
|
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||||
|
{children}
|
||||||
|
</DrawerPrimitive.Content>
|
||||||
|
</DrawerPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="drawer-header"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="drawer-footer"
|
||||||
|
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerTitle({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<DrawerPrimitive.Title
|
||||||
|
data-slot="drawer-title"
|
||||||
|
className={cn("text-foreground font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<DrawerPrimitive.Description
|
||||||
|
data-slot="drawer-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Drawer,
|
||||||
|
DrawerPortal,
|
||||||
|
DrawerOverlay,
|
||||||
|
DrawerTrigger,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerDescription,
|
||||||
|
}
|
||||||
@ -0,0 +1,255 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function DropdownMenu({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||||
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Trigger
|
||||||
|
data-slot="dropdown-menu-trigger"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuContent({
|
||||||
|
className,
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Portal>
|
||||||
|
<DropdownMenuPrimitive.Content
|
||||||
|
data-slot="dropdown-menu-content"
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</DropdownMenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Item
|
||||||
|
data-slot="dropdown-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.CheckboxItem
|
||||||
|
data-slot="dropdown-menu-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.RadioGroup
|
||||||
|
data-slot="dropdown-menu-radio-group"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.RadioItem
|
||||||
|
data-slot="dropdown-menu-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Label
|
||||||
|
data-slot="dropdown-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Separator
|
||||||
|
data-slot="dropdown-menu-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="dropdown-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSub({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||||
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
|
data-slot="dropdown-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto size-4" />
|
||||||
|
</DropdownMenuPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubContent
|
||||||
|
data-slot="dropdown-menu-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuShortcut,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
}
|
||||||
@ -0,0 +1,104 @@
|
|||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Empty({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty"
|
||||||
|
className={cn(
|
||||||
|
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-header"
|
||||||
|
className={cn(
|
||||||
|
"flex max-w-sm flex-col items-center gap-2 text-center",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyMediaVariants = cva(
|
||||||
|
"flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function EmptyMedia({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-icon"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(emptyMediaVariants({ variant, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-title"
|
||||||
|
className={cn("text-lg font-medium tracking-tight", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-content"
|
||||||
|
className={cn(
|
||||||
|
"flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Empty,
|
||||||
|
EmptyHeader,
|
||||||
|
EmptyTitle,
|
||||||
|
EmptyDescription,
|
||||||
|
EmptyContent,
|
||||||
|
EmptyMedia,
|
||||||
|
}
|
||||||
@ -0,0 +1,246 @@
|
|||||||
|
import { useMemo } from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
||||||
|
return (
|
||||||
|
<fieldset
|
||||||
|
data-slot="field-set"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-6",
|
||||||
|
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldLegend({
|
||||||
|
className,
|
||||||
|
variant = "legend",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
||||||
|
return (
|
||||||
|
<legend
|
||||||
|
data-slot="field-legend"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"mb-3 font-medium",
|
||||||
|
"data-[variant=legend]:text-base",
|
||||||
|
"data-[variant=label]:text-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-group"
|
||||||
|
className={cn(
|
||||||
|
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fieldVariants = cva(
|
||||||
|
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
orientation: {
|
||||||
|
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
|
||||||
|
horizontal: [
|
||||||
|
"flex-row items-center",
|
||||||
|
"[&>[data-slot=field-label]]:flex-auto",
|
||||||
|
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||||
|
],
|
||||||
|
responsive: [
|
||||||
|
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
|
||||||
|
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
|
||||||
|
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
orientation: "vertical",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Field({
|
||||||
|
className,
|
||||||
|
orientation = "vertical",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
data-slot="field"
|
||||||
|
data-orientation={orientation}
|
||||||
|
className={cn(fieldVariants({ orientation }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-content"
|
||||||
|
className={cn(
|
||||||
|
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Label>) {
|
||||||
|
return (
|
||||||
|
<Label
|
||||||
|
data-slot="field-label"
|
||||||
|
className={cn(
|
||||||
|
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
|
||||||
|
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
|
||||||
|
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-label"
|
||||||
|
className={cn(
|
||||||
|
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="field-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
|
||||||
|
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
|
||||||
|
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldSeparator({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
children?: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-separator"
|
||||||
|
data-content={!!children}
|
||||||
|
className={cn(
|
||||||
|
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<Separator className="absolute inset-0 top-1/2" />
|
||||||
|
{children && (
|
||||||
|
<span
|
||||||
|
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
|
||||||
|
data-slot="field-separator-content"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldError({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
errors,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
errors?: Array<{ message?: string } | undefined>
|
||||||
|
}) {
|
||||||
|
const content = useMemo(() => {
|
||||||
|
if (children) {
|
||||||
|
return children
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!errors?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const uniqueErrors = [
|
||||||
|
...new Map(errors.map((error) => [error?.message, error])).values(),
|
||||||
|
]
|
||||||
|
|
||||||
|
if (uniqueErrors?.length == 1) {
|
||||||
|
return uniqueErrors[0]?.message
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||||
|
{uniqueErrors.map(
|
||||||
|
(error, index) =>
|
||||||
|
error?.message && <li key={index}>{error.message}</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
)
|
||||||
|
}, [children, errors])
|
||||||
|
|
||||||
|
if (!content) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
data-slot="field-error"
|
||||||
|
className={cn("text-destructive text-sm font-normal", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Field,
|
||||||
|
FieldLabel,
|
||||||
|
FieldDescription,
|
||||||
|
FieldError,
|
||||||
|
FieldGroup,
|
||||||
|
FieldLegend,
|
||||||
|
FieldSeparator,
|
||||||
|
FieldSet,
|
||||||
|
FieldContent,
|
||||||
|
FieldTitle,
|
||||||
|
}
|
||||||
@ -0,0 +1,167 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import type * as LabelPrimitive from "@radix-ui/react-label"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
FormProvider,
|
||||||
|
useFormContext,
|
||||||
|
useFormState,
|
||||||
|
type ControllerProps,
|
||||||
|
type FieldPath,
|
||||||
|
type FieldValues,
|
||||||
|
} from "react-hook-form"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
|
||||||
|
const Form = FormProvider
|
||||||
|
|
||||||
|
type FormFieldContextValue<
|
||||||
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||||
|
> = {
|
||||||
|
name: TName
|
||||||
|
}
|
||||||
|
|
||||||
|
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||||
|
{} as FormFieldContextValue
|
||||||
|
)
|
||||||
|
|
||||||
|
const FormField = <
|
||||||
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||||
|
>({
|
||||||
|
...props
|
||||||
|
}: ControllerProps<TFieldValues, TName>) => {
|
||||||
|
return (
|
||||||
|
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||||
|
<Controller {...props} />
|
||||||
|
</FormFieldContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const useFormField = () => {
|
||||||
|
const fieldContext = React.useContext(FormFieldContext)
|
||||||
|
const itemContext = React.useContext(FormItemContext)
|
||||||
|
const { getFieldState } = useFormContext()
|
||||||
|
const formState = useFormState({ name: fieldContext.name })
|
||||||
|
const fieldState = getFieldState(fieldContext.name, formState)
|
||||||
|
|
||||||
|
if (!fieldContext) {
|
||||||
|
throw new Error("useFormField should be used within <FormField>")
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = itemContext
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: fieldContext.name,
|
||||||
|
formItemId: `${id}-form-item`,
|
||||||
|
formDescriptionId: `${id}-form-item-description`,
|
||||||
|
formMessageId: `${id}-form-item-message`,
|
||||||
|
...fieldState,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormItemContextValue = {
|
||||||
|
id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||||
|
{} as FormItemContextValue
|
||||||
|
)
|
||||||
|
|
||||||
|
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
const id = React.useId()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormItemContext.Provider value={{ id }}>
|
||||||
|
<div
|
||||||
|
data-slot="form-item"
|
||||||
|
className={cn("grid gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</FormItemContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
|
const { error, formItemId } = useFormField()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Label
|
||||||
|
data-slot="form-label"
|
||||||
|
data-error={!!error}
|
||||||
|
className={cn("data-[error=true]:text-destructive", className)}
|
||||||
|
htmlFor={formItemId}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||||
|
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Slot
|
||||||
|
data-slot="form-control"
|
||||||
|
id={formItemId}
|
||||||
|
aria-describedby={
|
||||||
|
!error
|
||||||
|
? `${formDescriptionId}`
|
||||||
|
: `${formDescriptionId} ${formMessageId}`
|
||||||
|
}
|
||||||
|
aria-invalid={!!error}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
const { formDescriptionId } = useFormField()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="form-description"
|
||||||
|
id={formDescriptionId}
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
const { error, formMessageId } = useFormField()
|
||||||
|
const body = error ? String(error?.message ?? "") : props.children
|
||||||
|
|
||||||
|
if (!body) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="form-message"
|
||||||
|
id={formMessageId}
|
||||||
|
className={cn("text-destructive text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{body}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
useFormField,
|
||||||
|
Form,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormControl,
|
||||||
|
FormDescription,
|
||||||
|
FormMessage,
|
||||||
|
FormField,
|
||||||
|
}
|
||||||
@ -0,0 +1,44 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function HoverCard({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||||
|
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function HoverCardTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function HoverCardContent({
|
||||||
|
className,
|
||||||
|
align = "center",
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
|
||||||
|
<HoverCardPrimitive.Content
|
||||||
|
data-slot="hover-card-content"
|
||||||
|
align={align}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</HoverCardPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { HoverCard, HoverCardTrigger, HoverCardContent }
|
||||||
@ -0,0 +1,170 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Input } from "@/components/ui/input"
|
||||||
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
|
|
||||||
|
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="input-group"
|
||||||
|
role="group"
|
||||||
|
className={cn(
|
||||||
|
"group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none",
|
||||||
|
"h-9 min-w-0 has-[>textarea]:h-auto",
|
||||||
|
|
||||||
|
// Variants based on alignment.
|
||||||
|
"has-[>[data-align=inline-start]]:[&>input]:pl-2",
|
||||||
|
"has-[>[data-align=inline-end]]:[&>input]:pr-2",
|
||||||
|
"has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3",
|
||||||
|
"has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3",
|
||||||
|
|
||||||
|
// Focus state.
|
||||||
|
"has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]",
|
||||||
|
|
||||||
|
// Error state.
|
||||||
|
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
|
||||||
|
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputGroupAddonVariants = cva(
|
||||||
|
"text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
align: {
|
||||||
|
"inline-start":
|
||||||
|
"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]",
|
||||||
|
"inline-end":
|
||||||
|
"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]",
|
||||||
|
"block-start":
|
||||||
|
"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5",
|
||||||
|
"block-end":
|
||||||
|
"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
align: "inline-start",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function InputGroupAddon({
|
||||||
|
className,
|
||||||
|
align = "inline-start",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
data-slot="input-group-addon"
|
||||||
|
data-align={align}
|
||||||
|
className={cn(inputGroupAddonVariants({ align }), className)}
|
||||||
|
onClick={(e) => {
|
||||||
|
if ((e.target as HTMLElement).closest("button")) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.currentTarget.parentElement?.querySelector("input")?.focus()
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputGroupButtonVariants = cva(
|
||||||
|
"text-sm shadow-none flex gap-2 items-center",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
size: {
|
||||||
|
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
|
||||||
|
sm: "h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5",
|
||||||
|
"icon-xs":
|
||||||
|
"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0",
|
||||||
|
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
size: "xs",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function InputGroupButton({
|
||||||
|
className,
|
||||||
|
type = "button",
|
||||||
|
variant = "ghost",
|
||||||
|
size = "xs",
|
||||||
|
...props
|
||||||
|
}: Omit<React.ComponentProps<typeof Button>, "size"> &
|
||||||
|
VariantProps<typeof inputGroupButtonVariants>) {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
type={type}
|
||||||
|
data-size={size}
|
||||||
|
variant={variant}
|
||||||
|
className={cn(inputGroupButtonVariants({ size }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground flex items-center gap-2 text-sm [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputGroupInput({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<Input
|
||||||
|
data-slot="input-group-control"
|
||||||
|
className={cn(
|
||||||
|
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputGroupTextarea({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"textarea">) {
|
||||||
|
return (
|
||||||
|
<Textarea
|
||||||
|
data-slot="input-group-control"
|
||||||
|
className={cn(
|
||||||
|
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
InputGroup,
|
||||||
|
InputGroupAddon,
|
||||||
|
InputGroupButton,
|
||||||
|
InputGroupText,
|
||||||
|
InputGroupInput,
|
||||||
|
InputGroupTextarea,
|
||||||
|
}
|
||||||
@ -0,0 +1,75 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { OTPInput, OTPInputContext } from "input-otp"
|
||||||
|
import { MinusIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function InputOTP({
|
||||||
|
className,
|
||||||
|
containerClassName,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof OTPInput> & {
|
||||||
|
containerClassName?: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<OTPInput
|
||||||
|
data-slot="input-otp"
|
||||||
|
containerClassName={cn(
|
||||||
|
"flex items-center gap-2 has-disabled:opacity-50",
|
||||||
|
containerClassName
|
||||||
|
)}
|
||||||
|
className={cn("disabled:cursor-not-allowed", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="input-otp-group"
|
||||||
|
className={cn("flex items-center", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputOTPSlot({
|
||||||
|
index,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
index: number
|
||||||
|
}) {
|
||||||
|
const inputOTPContext = React.useContext(OTPInputContext)
|
||||||
|
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="input-otp-slot"
|
||||||
|
data-active={isActive}
|
||||||
|
className={cn(
|
||||||
|
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{char}
|
||||||
|
{hasFakeCaret && (
|
||||||
|
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||||
|
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div data-slot="input-otp-separator" role="separator" {...props}>
|
||||||
|
<MinusIcon />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
|
||||||
@ -0,0 +1,21 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
data-slot="input"
|
||||||
|
className={cn(
|
||||||
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||||
|
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Input }
|
||||||
@ -0,0 +1,193 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="list"
|
||||||
|
data-slot="item-group"
|
||||||
|
className={cn("group/item-group flex flex-col", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Separator>) {
|
||||||
|
return (
|
||||||
|
<Separator
|
||||||
|
data-slot="item-separator"
|
||||||
|
orientation="horizontal"
|
||||||
|
className={cn("my-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemVariants = cva(
|
||||||
|
"group/item flex items-center border border-transparent text-sm rounded-md transition-colors [a]:hover:bg-accent/50 [a]:transition-colors duration-100 flex-wrap outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
outline: "border-border",
|
||||||
|
muted: "bg-muted/50",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "p-4 gap-4 ",
|
||||||
|
sm: "py-3 px-4 gap-2.5",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Item({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> &
|
||||||
|
VariantProps<typeof itemVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot : "div"
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="item"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(itemVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemMediaVariants = cva(
|
||||||
|
"flex shrink-0 items-center justify-center gap-2 group-has-[[data-slot=item-description]]/item:self-start [&_svg]:pointer-events-none group-has-[[data-slot=item-description]]/item:translate-y-0.5",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
icon: "size-8 border rounded-sm bg-muted [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
image:
|
||||||
|
"size-10 rounded-sm overflow-hidden [&_img]:size-full [&_img]:object-cover",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function ItemMedia({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-media"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(itemMediaVariants({ variant, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-content"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-1 flex-col gap-1 [&+[data-slot=item-content]]:flex-none",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-title"
|
||||||
|
className={cn(
|
||||||
|
"flex w-fit items-center gap-2 text-sm leading-snug font-medium",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="item-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground line-clamp-2 text-sm leading-normal font-normal text-balance",
|
||||||
|
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-actions"
|
||||||
|
className={cn("flex items-center gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-header"
|
||||||
|
className={cn(
|
||||||
|
"flex basis-full items-center justify-between gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex basis-full items-center justify-between gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Item,
|
||||||
|
ItemMedia,
|
||||||
|
ItemContent,
|
||||||
|
ItemActions,
|
||||||
|
ItemGroup,
|
||||||
|
ItemSeparator,
|
||||||
|
ItemTitle,
|
||||||
|
ItemDescription,
|
||||||
|
ItemHeader,
|
||||||
|
ItemFooter,
|
||||||
|
}
|
||||||
@ -0,0 +1,28 @@
|
|||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||||
|
return (
|
||||||
|
<kbd
|
||||||
|
data-slot="kbd"
|
||||||
|
className={cn(
|
||||||
|
"bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none",
|
||||||
|
"[&_svg:not([class*='size-'])]:size-3",
|
||||||
|
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<kbd
|
||||||
|
data-slot="kbd-group"
|
||||||
|
className={cn("inline-flex items-center gap-1", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Kbd, KbdGroup }
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Label({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<LabelPrimitive.Root
|
||||||
|
data-slot="label"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Label }
|
||||||
@ -0,0 +1,274 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as MenubarPrimitive from "@radix-ui/react-menubar"
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Menubar({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Root
|
||||||
|
data-slot="menubar"
|
||||||
|
className={cn(
|
||||||
|
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarMenu({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
|
||||||
|
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
|
||||||
|
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
|
||||||
|
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarTrigger({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Trigger
|
||||||
|
data-slot="menubar-trigger"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarContent({
|
||||||
|
className,
|
||||||
|
align = "start",
|
||||||
|
alignOffset = -4,
|
||||||
|
sideOffset = 8,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<MenubarPortal>
|
||||||
|
<MenubarPrimitive.Content
|
||||||
|
data-slot="menubar-content"
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</MenubarPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Item
|
||||||
|
data-slot="menubar-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.CheckboxItem
|
||||||
|
data-slot="menubar-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<MenubarPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</MenubarPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenubarPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.RadioItem
|
||||||
|
data-slot="menubar-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<MenubarPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</MenubarPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenubarPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Label
|
||||||
|
data-slot="menubar-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Separator
|
||||||
|
data-slot="menubar-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="menubar-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSub({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
|
||||||
|
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.SubTrigger
|
||||||
|
data-slot="menubar-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto h-4 w-4" />
|
||||||
|
</MenubarPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.SubContent
|
||||||
|
data-slot="menubar-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Menubar,
|
||||||
|
MenubarPortal,
|
||||||
|
MenubarMenu,
|
||||||
|
MenubarTrigger,
|
||||||
|
MenubarContent,
|
||||||
|
MenubarGroup,
|
||||||
|
MenubarSeparator,
|
||||||
|
MenubarLabel,
|
||||||
|
MenubarItem,
|
||||||
|
MenubarShortcut,
|
||||||
|
MenubarCheckboxItem,
|
||||||
|
MenubarRadioGroup,
|
||||||
|
MenubarRadioItem,
|
||||||
|
MenubarSub,
|
||||||
|
MenubarSubTrigger,
|
||||||
|
MenubarSubContent,
|
||||||
|
}
|
||||||
@ -0,0 +1,168 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||||
|
import { cva } from "class-variance-authority"
|
||||||
|
import { ChevronDownIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function NavigationMenu({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
viewport = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
|
||||||
|
viewport?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Root
|
||||||
|
data-slot="navigation-menu"
|
||||||
|
data-viewport={viewport}
|
||||||
|
className={cn(
|
||||||
|
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{viewport && <NavigationMenuViewport />}
|
||||||
|
</NavigationMenuPrimitive.Root>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuList({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.List
|
||||||
|
data-slot="navigation-menu-list"
|
||||||
|
className={cn(
|
||||||
|
"group flex flex-1 list-none items-center justify-center gap-1",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuItem({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Item
|
||||||
|
data-slot="navigation-menu-item"
|
||||||
|
className={cn("relative", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const navigationMenuTriggerStyle = cva(
|
||||||
|
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
|
||||||
|
)
|
||||||
|
|
||||||
|
function NavigationMenuTrigger({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Trigger
|
||||||
|
data-slot="navigation-menu-trigger"
|
||||||
|
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}{" "}
|
||||||
|
<ChevronDownIcon
|
||||||
|
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</NavigationMenuPrimitive.Trigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Content
|
||||||
|
data-slot="navigation-menu-content"
|
||||||
|
className={cn(
|
||||||
|
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
|
||||||
|
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuViewport({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"absolute top-full left-0 isolate z-50 flex justify-center"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<NavigationMenuPrimitive.Viewport
|
||||||
|
data-slot="navigation-menu-viewport"
|
||||||
|
className={cn(
|
||||||
|
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuLink({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Link
|
||||||
|
data-slot="navigation-menu-link"
|
||||||
|
className={cn(
|
||||||
|
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuIndicator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Indicator
|
||||||
|
data-slot="navigation-menu-indicator"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
|
||||||
|
</NavigationMenuPrimitive.Indicator>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
NavigationMenu,
|
||||||
|
NavigationMenuList,
|
||||||
|
NavigationMenuItem,
|
||||||
|
NavigationMenuContent,
|
||||||
|
NavigationMenuTrigger,
|
||||||
|
NavigationMenuLink,
|
||||||
|
NavigationMenuIndicator,
|
||||||
|
NavigationMenuViewport,
|
||||||
|
navigationMenuTriggerStyle,
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue