This commit is contained in:
邹方成 2025-10-11 21:19:20 +08:00
commit dfae1b91e4
98 changed files with 37281 additions and 0 deletions

13
.dockerignore Normal file
View File

@ -0,0 +1,13 @@
Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
.next
.git
package-lock.json
yarn.lock
pnpm-lock.yaml
test
*.log
local-*

49
.gitignore vendored Normal file
View File

@ -0,0 +1,49 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
local-*
.claude
.z-ai-config
dev.log
test
prompt
server.log

141
README.md Normal file
View File

@ -0,0 +1,141 @@
# 🚀 Welcome to Z.ai Code Scaffold
A modern, production-ready web application scaffold powered by cutting-edge technologies, designed to accelerate your development with [Z.ai](https://chat.z.ai)'s AI-powered coding assistance.
## ✨ Technology Stack
This scaffold provides a robust foundation built with:
### 🎯 Core Framework
- **⚡ Next.js 15** - The React framework for production with App Router
- **📘 TypeScript 5** - Type-safe JavaScript for better developer experience
- **🎨 Tailwind CSS 4** - Utility-first CSS framework for rapid UI development
### 🧩 UI Components & Styling
- **🧩 shadcn/ui** - High-quality, accessible components built on Radix UI
- **🎯 Lucide React** - Beautiful & consistent icon library
- **🌈 Framer Motion** - Production-ready motion library for React
- **🎨 Next Themes** - Perfect dark mode in 2 lines of code
### 📋 Forms & Validation
- **🎣 React Hook Form** - Performant forms with easy validation
- **✅ Zod** - TypeScript-first schema validation
### 🔄 State Management & Data Fetching
- **🐻 Zustand** - Simple, scalable state management
- **🔄 TanStack Query** - Powerful data synchronization for React
- **🌐 Axios** - Promise-based HTTP client
### 🗄️ Database & Backend
- **🗄️ Prisma** - Next-generation Node.js and TypeScript ORM
- **🔐 NextAuth.js** - Complete open-source authentication solution
### 🎨 Advanced UI Features
- **📊 TanStack Table** - Headless UI for building tables and datagrids
- **🖱️ DND Kit** - Modern drag and drop toolkit for React
- **📊 Recharts** - Redefined chart library built with React and D3
- **🖼️ Sharp** - High performance image processing
### 🌍 Internationalization & Utilities
- **🌍 Next Intl** - Internationalization library for Next.js
- **📅 Date-fns** - Modern JavaScript date utility library
- **🪝 ReactUse** - Collection of essential React hooks for modern development
## 🎯 Why This Scaffold?
- **🏎️ Fast Development** - Pre-configured tooling and best practices
- **🎨 Beautiful UI** - Complete shadcn/ui component library with advanced interactions
- **🔒 Type Safety** - Full TypeScript configuration with Zod validation
- **📱 Responsive** - Mobile-first design principles with smooth animations
- **🗄️ Database Ready** - Prisma ORM configured for rapid backend development
- **🔐 Auth Included** - NextAuth.js for secure authentication flows
- **📊 Data Visualization** - Charts, tables, and drag-and-drop functionality
- **🌍 i18n Ready** - Multi-language support with Next Intl
- **🚀 Production Ready** - Optimized build and deployment settings
- **🤖 AI-Friendly** - Structured codebase perfect for AI assistance
## 🚀 Quick Start
```bash
# Install dependencies
npm install
# Start development server
npm run dev
# Build for production
npm run build
# Start production server
npm start
```
Open [http://localhost:3000](http://localhost:3000) to see your application running.
## 🤖 Powered by Z.ai
This scaffold is optimized for use with [Z.ai](https://chat.z.ai) - your AI assistant for:
- **💻 Code Generation** - Generate components, pages, and features instantly
- **🎨 UI Development** - Create beautiful interfaces with AI assistance
- **🔧 Bug Fixing** - Identify and resolve issues with intelligent suggestions
- **📝 Documentation** - Auto-generate comprehensive documentation
- **🚀 Optimization** - Performance improvements and best practices
Ready to build something amazing? Start chatting with Z.ai at [chat.z.ai](https://chat.z.ai) and experience the future of AI-powered development!
## 📁 Project Structure
```
src/
├── app/ # Next.js App Router pages
├── components/ # Reusable React components
│ └── ui/ # shadcn/ui components
├── hooks/ # Custom React hooks
└── lib/ # Utility functions and configurations
```
## 🎨 Available Features & Components
This scaffold includes a comprehensive set of modern web development tools:
### 🧩 UI Components (shadcn/ui)
- **Layout**: Card, Separator, Aspect Ratio, Resizable Panels
- **Forms**: Input, Textarea, Select, Checkbox, Radio Group, Switch
- **Feedback**: Alert, Toast (Sonner), Progress, Skeleton
- **Navigation**: Breadcrumb, Menubar, Navigation Menu, Pagination
- **Overlay**: Dialog, Sheet, Popover, Tooltip, Hover Card
- **Data Display**: Badge, Avatar, Calendar
### 📊 Advanced Data Features
- **Tables**: Powerful data tables with sorting, filtering, pagination (TanStack Table)
- **Charts**: Beautiful visualizations with Recharts
- **Forms**: Type-safe forms with React Hook Form + Zod validation
### 🎨 Interactive Features
- **Animations**: Smooth micro-interactions with Framer Motion
- **Drag & Drop**: Modern drag-and-drop functionality with DND Kit
- **Theme Switching**: Built-in dark/light mode support
### 🔐 Backend Integration
- **Authentication**: Ready-to-use auth flows with NextAuth.js
- **Database**: Type-safe database operations with Prisma
- **API Client**: HTTP requests with Axios + TanStack Query
- **State Management**: Simple and scalable with Zustand
### 🌍 Production Features
- **Internationalization**: Multi-language support with Next Intl
- **Image Optimization**: Automatic image processing with Sharp
- **Type Safety**: End-to-end TypeScript with Zod validation
- **Essential Hooks**: 100+ useful React hooks with ReactUse for common patterns
## 🤝 Get Started with Z.ai
1. **Clone this scaffold** to jumpstart your project
2. **Visit [chat.z.ai](https://chat.z.ai)** to access your AI coding assistant
3. **Start building** with intelligent code generation and assistance
4. **Deploy with confidence** using the production-ready setup
---
Built with ❤️ for the developer community. Supercharged by [Z.ai](https://chat.z.ai) 🚀

21
components.json Normal file
View File

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

BIN
db/custom.db Normal file

Binary file not shown.

51
eslint.config.mjs Normal file
View File

@ -0,0 +1,51 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
rules: {
// TypeScript 相关规则
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/prefer-as-const": "off",
// React 相关规则
"react-hooks/exhaustive-deps": "off",
"react/no-unescaped-entities": "off",
"react/display-name": "off",
"react/prop-types": "off",
// Next.js 相关规则
"@next/next/no-img-element": "off",
"@next/next/no-html-link-for-pages": "off",
// 一般JavaScript规则
"prefer-const": "off", // 关闭prefer-const规则
"no-unused-vars": "off",
"no-console": "off",
"no-debugger": "off",
"no-empty": "off",
"no-irregular-whitespace": "off",
"no-case-declarations": "off",
"no-fallthrough": "off",
"no-mixed-spaces-and-tabs": "off",
"no-redeclare": "off",
"no-undef": "off",
"no-unreachable": "off",
"no-useless-escape": "off",
},
},
];
export default eslintConfig;

124
examples/websocket/page.tsx Normal file
View File

@ -0,0 +1,124 @@
'use client';
import { useEffect, useState } from 'react';
import { io } from 'socket.io-client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
type Message = {
text: string;
senderId: string;
timestamp: string;
}
export default function SocketDemo() {
const [messages, setMessages] = useState<Message[]>([]);
const [inputMessage, setInputMessage] = useState('');
const [socket, setSocket] = useState<any>(null);
const [isConnected, setIsConnected] = useState(false);
useEffect(() => {
const socketInstance = io({
path: '/api/socketio',
});
setSocket(socketInstance);
socketInstance.on('connect', () => {
setIsConnected(true);
});
socketInstance.on('disconnect', () => {
setIsConnected(false);
});
socketInstance.on('message', (msg: Message) => {
setMessages(prev => [...prev, msg]);
});
return () => {
socketInstance.disconnect();
};
}, []);
const sendMessage = () => {
if (socket && inputMessage.trim()) {
setMessages(prev => [...prev, {
text: inputMessage.trim(),
senderId: socket.id || 'user',
timestamp: new Date().toISOString()
}]);
socket.emit('message', {
text: inputMessage.trim(),
senderId: socket.id || 'user',
timestamp: new Date().toISOString()
});
setInputMessage('');
}
};
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
sendMessage();
}
};
return (
<div className="container mx-auto p-4 max-w-2xl">
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
WebSocket Demo
<span className={`text-sm px-2 py-1 rounded ${isConnected ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
{isConnected ? 'Connected' : 'Disconnected'}
</span>
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<ScrollArea className="h-80 w-full border rounded-md p-4">
<div className="space-y-2">
{messages.length === 0 ? (
<p className="text-gray-500 text-center">No messages yet</p>
) : (
messages.map((msg, index) => (
<div key={index} className="border-b pb-2 last:border-b-0">
<div className="flex justify-between items-start">
<div className="flex-1">
<p className="text-sm font-medium text-gray-700">
{msg.senderId}
</p>
<p className="text-gray-900">{msg.text}</p>
</div>
<span className="text-xs text-gray-500">
{new Date(msg.timestamp).toLocaleTimeString()}
</span>
</div>
</div>
))
)}
</div>
</ScrollArea>
<div className="flex space-x-2">
<Input
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="Type a message..."
disabled={!isConnected}
className="flex-1"
/>
<Button
onClick={sendMessage}
disabled={!isConnected || !inputMessage.trim()}
>
Send
</Button>
</div>
</CardContent>
</Card>
</div>
);
}

25
next.config.ts Normal file
View File

@ -0,0 +1,25 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
typescript: {
ignoreBuildErrors: true,
},
// 禁用 Next.js 热重载,由 nodemon 处理重编译
reactStrictMode: false,
webpack: (config, { dev }) => {
if (dev) {
// 禁用 webpack 的热模块替换
config.watchOptions = {
ignored: ['**/*'], // 忽略所有文件变化
};
}
return config;
},
eslint: {
// 构建时忽略ESLint错误
ignoreDuringBuilds: true,
},
};
export default nextConfig;

13833
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

100
package.json Normal file
View File

@ -0,0 +1,100 @@
{
"name": "nextjs_tailwind_shadcn_ts",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "nodemon --exec \"npx tsx server.ts\" --watch server.ts --watch src --ext ts,tsx,js,jsx 2>&1 | tee dev.log",
"build": "next build",
"start": "NODE_ENV=production tsx server.ts 2>&1 | tee server.log",
"lint": "next lint",
"db:push": "prisma db push",
"db:generate": "prisma generate",
"db:migrate": "prisma migrate dev",
"db:reset": "prisma migrate reset"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^5.1.1",
"@mdxeditor/editor": "^3.39.1",
"@prisma/client": "^6.11.1",
"@radix-ui/react-accordion": "^1.2.11",
"@radix-ui/react-alert-dialog": "^1.1.14",
"@radix-ui/react-aspect-ratio": "^1.1.7",
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-checkbox": "^1.3.2",
"@radix-ui/react-collapsible": "^1.1.11",
"@radix-ui/react-context-menu": "^2.2.15",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.15",
"@radix-ui/react-hover-card": "^1.1.14",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-menubar": "^1.1.15",
"@radix-ui/react-navigation-menu": "^1.2.13",
"@radix-ui/react-popover": "^1.1.14",
"@radix-ui/react-progress": "^1.1.7",
"@radix-ui/react-radio-group": "^1.3.7",
"@radix-ui/react-scroll-area": "^1.2.9",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slider": "^1.3.5",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-tabs": "^1.1.12",
"@radix-ui/react-toast": "^1.2.14",
"@radix-ui/react-toggle": "^1.1.9",
"@radix-ui/react-toggle-group": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.7",
"@reactuses/core": "^6.0.5",
"@tanstack/react-query": "^5.82.0",
"@tanstack/react-table": "^8.21.3",
"axios": "^1.10.0",
"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.23.24",
"input-otp": "^1.4.2",
"lucide-react": "^0.525.0",
"next": "15.3.5",
"next-auth": "^4.24.11",
"next-intl": "^4.3.4",
"next-themes": "^0.4.6",
"prisma": "^6.11.1",
"react": "^19.0.0",
"react-day-picker": "^9.8.0",
"react-dom": "^19.0.0",
"react-hook-form": "^7.60.0",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
"react-syntax-highlighter": "^15.6.1",
"recharts": "^2.15.4",
"sharp": "^0.34.3",
"socket.io": "^4.8.1",
"socket.io-client": "^4.8.1",
"sonner": "^2.0.6",
"tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7",
"tsx": "^4.20.3",
"uuid": "^11.1.0",
"vaul": "^1.1.2",
"z-ai-web-dev-sdk": "^0.0.10",
"zod": "^4.0.2",
"zustand": "^5.0.6"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.3.5",
"nodemon": "^3.1.10",
"tailwindcss": "^4",
"tw-animate-css": "^1.3.5",
"typescript": "^5.9.3"
}
}

9632
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

5
postcss.config.mjs Normal file
View File

@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

BIN
prisma/db/custom.db Normal file

Binary file not shown.

245
prisma/schema.prisma Normal file
View File

@ -0,0 +1,245 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
name String?
phone String?
avatar String?
wechatOpenid String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// 分销相关
distributorId String?
// 积分和等级
pointBalance Int @default(0)
membershipLevel String @default("explore") // explore,品鉴,调香
}
model Product {
id String @id @default(cuid())
name String
description String?
price Float
originalPrice Float?
images String // JSON array of image URLs
category String
tags String // JSON array
inventory Int @default(0)
salesCount Int @default(0)
status String @default("active") // active, inactive
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model GroupBuyConfig {
id String @id @default(cuid())
productId String @unique
// 阶梯拼团配置
tier3People Int @default(3)
tier3Discount Float @default(0.7) // 3人团7折
tier3Points Int @default(200) // 团长200积分
tier5People Int @default(5)
tier5Discount Float @default(0.5) // 5人团5折
tier5Points Int @default(300) // 团长300积分
// 时间配置
duration Int @default(24) // 小时
dailyLimit Int? // 每日限量
// 秒杀配置
flashSaleEnabled Boolean @default(false)
flashSalePrice Float?
flashSaleStock Int?
flashSaleTime String? // "10:00"
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model GroupBuy {
id String @id @default(cuid())
productId String
leaderId String
// 阶梯信息
targetPeople Int // 目标人数
currentPeople Int @default(1)
achievedTier String? // 达到的阶梯
// 价格信息
originalPrice Float
groupPrice Float
finalPrice Float? // 最终成交价
// 时间信息
startTime DateTime @default(now())
endTime DateTime
successTime DateTime?
// 状态
status String @default("active") // active, success, failed, expired
// 溯源码
traceCode String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model GroupMember {
id String @id @default(cuid())
groupBuyId String
userId String
inviterId String? // 邀请人ID
joinTime DateTime @default(now())
isLeader Boolean @default(false)
// 避免重复参团
@@unique([groupBuyId, userId])
}
model Order {
id String @id @default(cuid())
orderNo String @unique
userId String
productId String
groupBuyId String?
// 价格信息
originalPrice Float
finalPrice Float
discountAmount Float @default(0)
// 订单信息
quantity Int @default(1)
status String @default("pending") // pending, paid, shipped, delivered, cancelled
paymentMethod String?
paymentTime DateTime?
// 物流信息
trackingNumber String?
logisticsInfo String? // JSON
// 溯源信息
traceCode String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Commission {
id String @id @default(cuid())
orderId String
distributorId String
// 佣金信息
type String // direct, indirect
amount Float
rate Float // 佣金比例
// 状态
status String @default("pending") // pending, settled, cancelled
settledTime DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Subscription {
id String @id @default(cuid())
userId String @unique
// 订阅配置
plan String // monthly, quarterly
status String @default("active") // active, paused, cancelled
// 配送配置
deliveryFrequency String @default("monthly") // monthly, semimonthly
deliveryDay Int @default(5) // 每月几号
excludedScents String // JSON array of excluded scents
// 盲盒配置
unlockedScents String // JSON array of unlocked scents
// 订阅时间
startTime DateTime @default(now())
endTime DateTime?
nextDelivery DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model SubscriptionConfig {
id String @id @default(cuid())
productId String @unique
// 订阅价格
monthlyPrice Float
quarterlyPrice Float
// 会员折扣
exploreDiscount Float @default(0.95) // 95折
tastingDiscount Float @default(0.85) // 85折
perfumerDiscount Float? // 调香师专属
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Point {
id String @id @default(cuid())
userId String
// 积分信息
amount Int
type String // earn, spend
source String // purchase, group_buy, distribution, ugc, etc.
description String?
// 关联信息
relatedId String? // 关联订单ID等
relatedType String? // order, group_buy, etc.
createdAt DateTime @default(now())
}
model UgcContent {
id String @id @default(cuid())
userId String
// 内容信息
type String // review, tutorial, story
title String
content String
images String // JSON array
tags String // JSON array
// 状态
status String @default("pending") // pending, approved, rejected
// 互动数据
likes Int @default(0)
views Int @default(0)
// 奖励
pointsAwarded Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

118
public/logo.svg Normal file
View File

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" viewBox="0 0 2000 1700">
<defs>
<style>
.cls-1 {
fill: url(#gradient1);
}
.cls-2 {
fill: url(#gradient2);
}
.cls-3 {
fill: url(#gradient3);
}
.glow {
filter: url(#glow-filter);
}
.pulse {
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 0.4; }
50% { opacity: 1; }
}
@keyframes shimmer {
0% { transform: translateX(-200%); }
100% { transform: translateX(200%); }
}
.shimmer {
animation: shimmer 3s ease-in-out infinite;
}
</style>
<!-- 发光滤镜 -->
<filter id="glow-filter" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="8" result="coloredBlur"/>
<feMerge>
<feMergeNode in="coloredBlur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
<!-- 动态渐变 -->
<linearGradient id="gradient1" x1="531.58" y1="-4.02" x2="531.58" y2="1661.41" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#070606">
<animate attributeName="stop-color" values="#070606;#5a5a5a;#070606" dur="1.8s" repeatCount="indefinite"/>
</stop>
<stop offset=".37" stop-color="#1b1b1b">
<animate attributeName="stop-color" values="#1b1b1b;#888888;#1b1b1b" dur="1.8s" repeatCount="indefinite"/>
</stop>
<stop offset="1" stop-color="#3b3b3b">
<animate attributeName="stop-color" values="#3b3b3b;#cccccc;#3b3b3b" dur="1.8s" repeatCount="indefinite"/>
</stop>
</linearGradient>
<linearGradient id="gradient2" x1="1000" y1="-4.02" x2="1000" y2="1661.41" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#070606">
<animate attributeName="stop-color" values="#070606;#5a5a5a;#070606" dur="1.8s" repeatCount="indefinite" begin="0.6s"/>
</stop>
<stop offset=".37" stop-color="#1b1b1b">
<animate attributeName="stop-color" values="#1b1b1b;#888888;#1b1b1b" dur="1.8s" repeatCount="indefinite" begin="0.6s"/>
</stop>
<stop offset="1" stop-color="#3b3b3b">
<animate attributeName="stop-color" values="#3b3b3b;#cccccc;#3b3b3b" dur="1.8s" repeatCount="indefinite" begin="0.6s"/>
</stop>
</linearGradient>
<linearGradient id="gradient3" x1="1462.04" y1="-4.02" x2="1462.04" y2="1661.41" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#070606">
<animate attributeName="stop-color" values="#070606;#5a5a5a;#070606" dur="1.8s" repeatCount="indefinite" begin="1.2s"/>
</stop>
<stop offset=".37" stop-color="#1b1b1b">
<animate attributeName="stop-color" values="#1b1b1b;#888888;#1b1b1b" dur="1.8s" repeatCount="indefinite" begin="1.2s"/>
</stop>
<stop offset="1" stop-color="#3b3b3b">
<animate attributeName="stop-color" values="#3b3b3b;#cccccc;#3b3b3b" dur="1.8s" repeatCount="indefinite" begin="1.2s"/>
</stop>
</linearGradient>
<!-- 光晕渐变 -->
<radialGradient id="glow-gradient" cx="50%" cy="50%" r="50%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.3"/>
<stop offset="70%" stop-color="#888888" stop-opacity="0.1"/>
<stop offset="100%" stop-color="#ffffff" stop-opacity="0"/>
</radialGradient>
<!-- 闪光效果 -->
<linearGradient id="shine-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0"/>
<stop offset="45%" stop-color="#ffffff" stop-opacity="0"/>
<stop offset="50%" stop-color="#ffffff" stop-opacity="0.8"/>
<stop offset="55%" stop-color="#ffffff" stop-opacity="0"/>
<stop offset="100%" stop-color="#ffffff" stop-opacity="0"/>
</linearGradient>
<!-- 裁切路径 -->
<clipPath id="shape-clip">
<polygon points="1008.73 0 827.29 251.03 54.43 251.03 235.74 0 1008.73 0"/>
<polygon points="1937.79 1449.1 1756.47 1700 986.3 1700 1167.48 1449.1 1937.79 1449.1"/>
<polygon points="2000 0 771.98 1700 0 1700 1228.02 0 2000 0"/>
</clipPath>
</defs>
<g class="glow breathe">
<g class="pulse wave-effect">
<!-- 主要几何形状 -->
<polygon class="cls-1" points="1008.73 0 827.29 251.03 54.43 251.03 235.74 0 1008.73 0"/>
<polygon class="cls-3" points="1937.79 1449.1 1756.47 1700 986.3 1700 1167.48 1449.1 1937.79 1449.1"/>
<polygon class="cls-2" points="2000 0 771.98 1700 0 1700 1228.02 0 2000 0"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

14
public/robots.txt Normal file
View File

@ -0,0 +1,14 @@
User-agent: Googlebot
Allow: /
User-agent: Bingbot
Allow: /
User-agent: Twitterbot
Allow: /
User-agent: facebookexternalhit
Allow: /
User-agent: *
Allow: /

58
server.ts Normal file
View File

@ -0,0 +1,58 @@
// server.ts - Next.js Standalone + Socket.IO
import { setupSocket } from '@/lib/socket';
import { createServer } from 'http';
import { Server } from 'socket.io';
import next from 'next';
const dev = process.env.NODE_ENV !== 'production';
const currentPort = 3000;
const hostname = '0.0.0.0';
// Custom server with Socket.IO integration
async function createCustomServer() {
try {
// Create Next.js app
const nextApp = next({
dev,
dir: process.cwd(),
// In production, use the current directory where .next is located
conf: dev ? undefined : { distDir: './.next' }
});
await nextApp.prepare();
const handle = nextApp.getRequestHandler();
// Create HTTP server that will handle both Next.js and Socket.IO
const server = createServer((req, res) => {
// Skip socket.io requests from Next.js handler
if (req.url?.startsWith('/api/socketio')) {
return;
}
handle(req, res);
});
// Setup Socket.IO
const io = new Server(server, {
path: '/api/socketio',
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
setupSocket(io);
// Start the server
server.listen(currentPort, hostname, () => {
console.log(`> Ready on http://${hostname}:${currentPort}`);
console.log(`> Socket.IO server running at ws://${hostname}:${currentPort}/api/socketio`);
});
} catch (err) {
console.error('Server startup error:', err);
process.exit(1);
}
}
// Start the server
createCustomServer();

View File

@ -0,0 +1,249 @@
'use client'
import { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { ArrowLeft, Gift, Users, Eye, Trophy, Calendar, User } from 'lucide-react'
import LotteryWheel from '@/components/lottery-wheel'
import Link from 'next/link'
export default function ActivityDetailPage() {
const params = useParams()
const activityId = params.id as string
const [activity, setActivity] = useState<any>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
// 模拟获取活动详情
const fetchActivity = async () => {
try {
// 这里应该调用API获取活动详情
const mockActivity = {
id: activityId,
title: '幸运大转盘',
description: '欢迎参与我们的幸运大转盘抽奖活动多种奖品等你来拿100%中奖!',
status: 'active',
startDate: '2025-03-26T00:00:00Z',
endDate: '2025-04-02T23:59:59Z',
maxParticipants: 1000,
creator: {
name: '微购商城',
avatar: '/logo.svg'
},
stats: {
exposure: 1250,
participants: 856,
winners: 856,
claims: 723
},
prizes: [
{ id: '1', name: '5元无门槛券', color: '#ef4444', probability: 30, remaining: 97, total: 100 },
{ id: '2', name: '10元优惠券', color: '#f97316', probability: 20, remaining: 45, total: 50 },
{ id: '3', name: '谢谢参与', color: '#6b7280', probability: 50, remaining: 950, total: 1000 }
],
recentWinners: [
{ name: '张*', prize: '5元无门槛券', time: '2分钟前', avatar: '张' },
{ name: '李**', prize: '10元优惠券', time: '5分钟前', avatar: '李' },
{ name: '王*', prize: '5元无门槛券', time: '8分钟前', avatar: '王' },
{ name: '赵**', prize: '谢谢参与', time: '10分钟前', avatar: '赵' }
],
rules: [
'每位用户每日最多可参与3次抽奖',
'奖品数量有限,先到先得',
'优惠券有效期7天请及时使用',
'禁止使用外挂等作弊行为,一经发现将取消中奖资格'
]
}
setActivity(mockActivity)
} catch (error) {
console.error('获取活动详情失败:', error)
} finally {
setLoading(false)
}
}
fetchActivity()
}, [activityId])
const handleSpinComplete = (prize: any) => {
console.log('中奖了:', prize)
// 这里可以刷新中奖记录
}
if (loading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-red-500 mx-auto"></div>
<p className="mt-4 text-gray-500">...</p>
</div>
</div>
)
}
if (!activity) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<Card className="max-w-md w-full">
<CardContent className="py-12 text-center">
<Gift className="w-12 h-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-gray-900 mb-2"></h3>
<p className="text-gray-500 mb-4"></p>
<Link href="/">
<Button className="bg-red-500 hover:bg-red-600">
</Button>
</Link>
</CardContent>
</Card>
</div>
)
}
return (
<div className="min-h-screen bg-gray-50">
{/* Header */}
<div className="bg-white border-b">
<div className="max-w-4xl mx-auto px-4 py-4">
<div className="flex items-center gap-4">
<Link href="/">
<Button variant="ghost" size="sm">
<ArrowLeft className="w-4 h-4 mr-1" />
</Button>
</Link>
<h1 className="text-xl font-bold text-gray-900">{activity.title}</h1>
<Badge className={activity.status === 'active' ? 'bg-green-500' : 'bg-gray-500'}>
{activity.status === 'active' ? '进行中' : '已结束'}
</Badge>
</div>
</div>
</div>
{/* Main Content */}
<div className="max-w-4xl mx-auto px-4 py-6">
<div className="grid lg:grid-cols-2 gap-6">
{/* 左侧:转盘 */}
<div>
<LotteryWheel
prizes={activity.prizes}
onSpinComplete={handleSpinComplete}
disabled={activity.status !== 'active'}
/>
</div>
{/* 右侧:活动信息 */}
<div className="space-y-4">
{/* 活动描述 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<p className="text-gray-600">{activity.description}</p>
<div className="flex items-center gap-4 mt-4 text-sm text-gray-500">
<div className="flex items-center gap-1">
<User className="w-4 h-4" />
<span>{activity.creator.name}</span>
</div>
<div className="flex items-center gap-1">
<Calendar className="w-4 h-4" />
<span>{new Date(activity.startDate).toLocaleDateString()} - {new Date(activity.endDate).toLocaleDateString()}</span>
</div>
</div>
</CardContent>
</Card>
{/* 数据统计 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4">
<div className="text-center p-3 bg-gray-50 rounded-lg">
<div className="flex items-center justify-center gap-1 text-gray-500 mb-1">
<Eye className="w-4 h-4" />
<span className="text-xs"></span>
</div>
<p className="text-lg font-bold text-gray-900">{activity.stats.exposure.toLocaleString()}</p>
</div>
<div className="text-center p-3 bg-gray-50 rounded-lg">
<div className="flex items-center justify-center gap-1 text-gray-500 mb-1">
<Users className="w-4 h-4" />
<span className="text-xs"></span>
</div>
<p className="text-lg font-bold text-gray-900">{activity.stats.participants.toLocaleString()}</p>
</div>
<div className="text-center p-3 bg-gray-50 rounded-lg">
<div className="flex items-center justify-center gap-1 text-gray-500 mb-1">
<Trophy className="w-4 h-4" />
<span className="text-xs"></span>
</div>
<p className="text-lg font-bold text-gray-900">{activity.stats.winners.toLocaleString()}</p>
</div>
<div className="text-center p-3 bg-gray-50 rounded-lg">
<div className="flex items-center justify-center gap-1 text-gray-500 mb-1">
<Gift className="w-4 h-4" />
<span className="text-xs"></span>
</div>
<p className="text-lg font-bold text-gray-900">{activity.stats.claims.toLocaleString()}</p>
</div>
</div>
</CardContent>
</Card>
{/* 最近中奖 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
{activity.recentWinners.map((winner: any, index: number) => (
<div key={index} className="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
<span className="text-xs font-semibold text-red-600">{winner.avatar}</span>
</div>
<div>
<p className="text-sm font-medium text-gray-900">{winner.name}</p>
<p className="text-xs text-gray-500">{winner.time}</p>
</div>
</div>
<Badge variant="secondary" className="text-xs">
{winner.prize}
</Badge>
</div>
))}
</div>
</CardContent>
</Card>
{/* 活动规则 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<ul className="space-y-2 text-sm text-gray-600">
{activity.rules.map((rule: string, index: number) => (
<li key={index} className="flex items-start gap-2">
<span className="text-red-500 mt-0.5"></span>
<span>{rule}</span>
</li>
))}
</ul>
</CardContent>
</Card>
</div>
</div>
</div>
</div>
)
}

View File

@ -0,0 +1,106 @@
import { NextRequest, NextResponse } from 'next/server'
interface Activity {
id: string
title: string
description: string
startDate: string
endDate: string
maxParticipants: number
prizes: Array<{
id: string
name: string
total: number
probability: number
color: string
}>
status: 'active' | 'ended' | 'draft'
createdAt: string
}
// 模拟数据库存储
let activities: Activity[] = [
{
id: '1',
title: '幸运大转盘',
description: '体验版抽奖活动',
startDate: '2025-03-26T00:00:00Z',
endDate: '2025-04-02T23:59:59Z',
maxParticipants: 1000,
prizes: [
{ id: '1', name: '5元无门槛券', total: 100, probability: 30, color: '#ef4444' },
{ id: '2', name: '10元优惠券', total: 50, probability: 20, color: '#f97316' },
{ id: '3', name: '谢谢参与', total: 1000, probability: 50, color: '#6b7280' }
],
status: 'ended',
createdAt: '2025-03-26T00:00:00Z'
}
]
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const status = searchParams.get('status')
let filteredActivities = activities
if (status) {
filteredActivities = activities.filter(activity => activity.status === status)
}
return NextResponse.json({
success: true,
data: filteredActivities
})
} catch (error) {
console.error('获取活动列表失败:', error)
return NextResponse.json({
success: false,
error: '获取活动列表失败'
}, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const activityData: Omit<Activity, 'id' | 'createdAt'> = await request.json()
// 验证必填字段
if (!activityData.title || !activityData.startDate || !activityData.endDate) {
return NextResponse.json({
success: false,
error: '缺少必填字段'
}, { status: 400 })
}
// 验证概率总和
const totalProbability = activityData.prizes.reduce((sum, prize) => sum + prize.probability, 0)
if (Math.abs(totalProbability - 100) > 0.1) {
return NextResponse.json({
success: false,
error: '奖品概率总和必须等于100%'
}, { status: 400 })
}
// 创建新活动
const newActivity: Activity = {
...activityData,
id: Date.now().toString(),
createdAt: new Date().toISOString()
}
activities.push(newActivity)
return NextResponse.json({
success: true,
data: newActivity,
message: '活动创建成功'
})
} catch (error) {
console.error('创建活动失败:', error)
return NextResponse.json({
success: false,
error: '创建活动失败'
}, { status: 500 })
}
}

View File

@ -0,0 +1,5 @@
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Good!" });
}

View File

@ -0,0 +1,164 @@
import { NextRequest, NextResponse } from 'next/server'
import ZAI from 'z-ai-web-dev-sdk'
interface SpinRequest {
activityId: string
userId: string
prizes: Array<{
id: string
name: string
probability: number
remaining: number
total: number
}>
}
interface SpinResponse {
success: boolean
prize?: {
id: string
name: string
}
message?: string
error?: string
}
export async function POST(request: NextRequest): Promise<NextResponse<SpinResponse>> {
try {
const body: SpinRequest = await request.json()
const { activityId, userId, prizes } = body
// 验证请求参数
if (!activityId || !userId || !prizes || !Array.isArray(prizes)) {
return NextResponse.json({
success: false,
error: '请求参数不完整'
}, { status: 400 })
}
// 检查用户今日抽奖次数(这里简化处理,实际应该从数据库查询)
const dailyLimit = 3
const userSpinsToday = await getUserSpinsToday(userId)
if (userSpinsToday >= dailyLimit) {
return NextResponse.json({
success: false,
error: `今日抽奖次数已达上限(${dailyLimit}次)`
}, { status: 429 })
}
// 过滤掉已发完的奖品
const availablePrizes = prizes.filter(prize => prize.remaining > 0)
if (availablePrizes.length === 0) {
return NextResponse.json({
success: false,
error: '奖品已发完'
}, { status: 400 })
}
// 计算中奖结果
const selectedPrize = calculatePrize(availablePrizes)
if (!selectedPrize) {
return NextResponse.json({
success: false,
error: '未能计算出中奖结果'
}, { status: 500 })
}
// 记录抽奖结果
await recordSpinResult({
activityId,
userId,
prizeId: selectedPrize.id,
prizeName: selectedPrize.name,
spinTime: new Date().toISOString()
})
// 更新奖品剩余数量
await updatePrizeRemaining(activityId, selectedPrize.id, -1)
return NextResponse.json({
success: true,
prize: {
id: selectedPrize.id,
name: selectedPrize.name
},
message: '恭喜中奖!'
})
} catch (error) {
console.error('抽奖处理失败:', error)
return NextResponse.json({
success: false,
error: '服务器内部错误'
}, { status: 500 })
}
}
// 计算中奖结果
function calculatePrize(prizes: SpinRequest['prizes']) {
const totalProbability = prizes.reduce((sum, prize) => sum + prize.probability, 0)
const random = Math.random() * totalProbability
let accumulated = 0
for (const prize of prizes) {
accumulated += prize.probability
if (random <= accumulated) {
return prize
}
}
return prizes[prizes.length - 1] // 返回最后一个奖品作为兜底
}
// 获取用户今日抽奖次数(模拟实现)
async function getUserSpinsToday(userId: string): Promise<number> {
// 这里应该从数据库查询用户今日抽奖次数
// 为了演示,返回一个随机数
return Math.floor(Math.random() * 3)
}
// 记录抽奖结果(模拟实现)
async function recordSpinResult(data: {
activityId: string
userId: string
prizeId: string
prizeName: string
spinTime: string
}) {
// 这里应该将抽奖结果保存到数据库
console.log('记录抽奖结果:', data)
// 可以在这里集成AI服务来生成个性化的中奖消息
try {
const zai = await ZAI.create()
const completion = await zai.chat.completions.create({
messages: [
{
role: 'system',
content: '你是一个抽奖系统的助手,需要为用户生成个性化的中奖祝福语。'
},
{
role: 'user',
content: `用户抽中了${data.prizeName},请生成一个简短、有趣的祝福语。`
}
],
max_tokens: 50,
temperature: 0.8
})
const blessing = completion.choices[0]?.message?.content
console.log('AI生成的祝福语:', blessing)
} catch (error) {
console.error('生成祝福语失败:', error)
}
}
// 更新奖品剩余数量(模拟实现)
async function updatePrizeRemaining(activityId: string, prizeId: string, change: number) {
// 这里应该更新数据库中的奖品剩余数量
console.log(`更新奖品剩余数量: 活动${activityId}, 奖品${prizeId}, 变化${change}`)
}

View File

@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ width: string; height: string }> }
) {
const { width, height } = await params
// 生成一个简单的SVG占位符图片
const svg = `
<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="#f3f4f6"/>
<text x="50%" y="50%" text-anchor="middle" dy=".3em" fill="#9ca3af" font-family="Arial, sans-serif" font-size="14">
${width}x${height}
</text>
</svg>
`
return new NextResponse(svg, {
headers: {
'Content-Type': 'image/svg+xml',
'Cache-Control': 'public, max-age=86400', // 缓存1天
},
})
}

View File

@ -0,0 +1,569 @@
'use client'
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Separator } from '@/components/ui/separator'
import {
Users,
TrendingUp,
DollarSign,
Gift,
Crown,
Target,
Award,
Copy,
MessageCircle,
Download,
Star,
Zap,
ArrowUpRight,
Calendar,
ShoppingBag,
Share2,
ShoppingCart,
Home
} from 'lucide-react'
export default function DistributionPage() {
const [activeTab, setActiveTab] = useState('overview')
// 模拟数据
const stats = {
totalCommission: 2580.50,
todayCommission: 156.00,
teamSize: 23,
activeMembers: 18,
level: '品鉴分销员',
nextLevelProgress: 65,
monthlyOrders: 45,
monthlyRevenue: 8950.00
}
const teamMembers = [
{
id: '1',
name: '小美',
avatar: '小',
level: '探索分销员',
joinTime: '2025-03-15',
totalOrders: 15,
commission: 234.50,
status: 'active',
monthlyOrders: 8,
avatarUrl: '/api/placeholder/40/40'
},
{
id: '2',
name: '香香公主',
avatar: '香',
level: '品鉴分销员',
joinTime: '2025-03-10',
totalOrders: 28,
commission: 456.80,
status: 'active',
monthlyOrders: 12,
avatarUrl: '/api/placeholder/40/40'
},
{
id: '3',
name: '花仙子',
avatar: '花',
level: '调香分销员',
joinTime: '2025-03-01',
totalOrders: 42,
commission: 789.20,
status: 'active',
monthlyOrders: 18,
avatarUrl: '/api/placeholder/40/40'
}
]
const commissions = [
{
id: '1',
orderNo: 'ORD20250402001',
customerName: '张小姐',
productName: '经典玫瑰香水30ml',
type: 'direct',
amount: 19.90,
rate: 0.10,
status: 'settled',
time: '2025-04-02 14:30',
orderAmount: 199.00
},
{
id: '2',
orderNo: 'ORD20250402002',
customerName: '李女士',
productName: '薰衣草精油礼盒',
type: 'indirect',
amount: 14.95,
rate: 0.05,
status: 'pending',
time: '2025-04-02 13:15',
orderAmount: 299.00
},
{
id: '3',
orderNo: 'ORD20250402003',
customerName: '王小姐',
productName: '小样体验包',
type: 'direct',
amount: 0.10,
rate: 0.10,
status: 'settled',
time: '2025-04-02 10:45',
orderAmount: 1.00
}
]
const materials = [
{
id: '1',
title: '宝妈话术模板',
content: '自用省50分享赚100香氛好物自用省钱分享赚钱',
category: '话术',
usage: 1250,
rating: 4.8,
image: '/api/placeholder/200/150'
},
{
id: '2',
title: '产品种草文案',
content: '这款玫瑰香水太绝了!留香一整天,闺蜜都问我要链接',
category: '文案',
usage: 890,
rating: 4.6,
image: '/api/placeholder/200/150'
},
{
id: '3',
title: '拼团分享海报',
content: '精美海报模板,一键生成分享图',
category: '海报',
usage: 2100,
rating: 4.9,
image: '/api/placeholder/200/150'
},
{
id: '4',
title: '产品介绍视频',
content: '专业拍摄的产品展示视频,适合短视频平台',
category: '视频',
usage: 650,
rating: 4.7,
image: '/api/placeholder/200/150'
}
]
const tasks = [
{
id: '1',
title: '邀请3位好友',
description: '成功邀请3位好友注册并完成首单',
reward: '解锁高佣金商品推广权',
progress: 2,
target: 3,
status: 'in_progress',
icon: Users,
color: 'blue'
},
{
id: '2',
title: '月销10单',
description: '本月完成10笔有效订单',
reward: '获得限量香氛礼品',
progress: 7,
target: 10,
status: 'in_progress',
icon: ShoppingBag,
color: 'green'
},
{
id: '3',
title: '团队建设',
description: '团队人数达到20人',
reward: '晋升为调香分销员',
progress: 23,
target: 20,
status: 'completed',
icon: Crown,
color: 'purple'
}
]
const copyInviteCode = async () => {
const inviteCode = 'FRAGRANCE2025'
const inviteUrl = `${window.location.origin}/register?code=${inviteCode}`
try {
await navigator.clipboard.writeText(inviteUrl)
alert('邀请链接已复制到剪贴板')
} catch (error) {
console.error('复制失败')
}
}
const copyMaterial = async (content: string) => {
try {
await navigator.clipboard.writeText(content)
alert('内容已复制到剪贴板')
} catch (error) {
console.error('复制失败')
}
}
return (
<div className="min-h-screen bg-gray-50">
{/* Header */}
<div className="bg-gradient-to-r from-purple-600 to-pink-600 text-white">
<div className="max-w-6xl mx-auto px-4 py-8">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-16 h-16 bg-white/20 backdrop-blur rounded-full flex items-center justify-center">
<Crown className="w-8 h-8 text-white" />
</div>
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-purple-100 mt-1">{stats.level} · {stats.teamSize} </p>
</div>
</div>
<div className="text-right">
<p className="text-sm text-purple-100"></p>
<p className="text-3xl font-bold">¥{stats.totalCommission.toFixed(2)}</p>
<Button
onClick={copyInviteCode}
className="mt-2 bg-white text-purple-600 hover:bg-purple-50"
>
<Copy className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
</div>
</div>
<div className="max-w-6xl mx-auto px-4 py-6">
{/* 统计卡片 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
<Card className="bg-gradient-to-br from-green-50 to-green-100 border-green-200">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-green-600"></p>
<p className="text-2xl font-bold text-green-700">¥{stats.todayCommission.toFixed(2)}</p>
<p className="text-xs text-green-600 mt-1">+12.5% </p>
</div>
<div className="w-12 h-12 bg-green-500 rounded-full flex items-center justify-center">
<DollarSign className="w-6 h-6 text-white" />
</div>
</div>
</CardContent>
</Card>
<Card className="bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-blue-600"></p>
<p className="text-2xl font-bold text-blue-700">{stats.teamSize}</p>
<p className="text-xs text-blue-600 mt-1"> {stats.activeMembers} </p>
</div>
<div className="w-12 h-12 bg-blue-500 rounded-full flex items-center justify-center">
<Users className="w-6 h-6 text-white" />
</div>
</div>
</CardContent>
</Card>
<Card className="bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-purple-600"></p>
<p className="text-2xl font-bold text-purple-700">{stats.monthlyOrders}</p>
<p className="text-xs text-purple-600 mt-1">¥{stats.monthlyRevenue.toFixed(0)}</p>
</div>
<div className="w-12 h-12 bg-purple-500 rounded-full flex items-center justify-center">
<ShoppingBag className="w-6 h-6 text-white" />
</div>
</div>
</CardContent>
</Card>
<Card className="bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-orange-600"></p>
<p className="text-2xl font-bold text-orange-700">{stats.nextLevelProgress}%</p>
<Progress value={stats.nextLevelProgress} className="h-1 mt-2" />
</div>
<div className="w-12 h-12 bg-orange-500 rounded-full flex items-center justify-center">
<Award className="w-6 h-6 text-white" />
</div>
</div>
</CardContent>
</Card>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="overview"></TabsTrigger>
<TabsTrigger value="team"></TabsTrigger>
<TabsTrigger value="materials"></TabsTrigger>
<TabsTrigger value="tasks"></TabsTrigger>
</TabsList>
{/* 数据概览 */}
<TabsContent value="overview" className="mt-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 佣金明细 */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle></CardTitle>
<Button variant="outline" size="sm">
<Calendar className="w-4 h-4 mr-2" />
</Button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{commissions.map((commission) => (
<div key={commission.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium">{commission.customerName}</span>
<Badge variant={commission.type === 'direct' ? 'default' : 'secondary'}>
{commission.type === 'direct' ? '直推' : '间推'}
</Badge>
<Badge variant={commission.status === 'settled' ? 'default' : 'outline'}>
{commission.status === 'settled' ? '已结算' : '待结算'}
</Badge>
</div>
<p className="text-sm text-gray-600">{commission.productName}</p>
<p className="text-xs text-gray-500">{commission.orderNo} · {commission.time}</p>
</div>
<div className="text-right">
<p className="text-lg font-bold text-green-600">¥{commission.amount.toFixed(2)}</p>
<p className="text-xs text-gray-500">{(commission.rate * 100).toFixed(0)}%</p>
<p className="text-xs text-gray-400">¥{commission.orderAmount}</p>
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* 业绩趋势 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="text-center p-4 bg-blue-50 rounded-lg">
<p className="text-sm text-blue-600"></p>
<p className="text-xl font-bold text-blue-700">¥568.00</p>
<p className="text-xs text-blue-600">+8.2%</p>
</div>
<div className="text-center p-4 bg-green-50 rounded-lg">
<p className="text-sm text-green-600"></p>
<p className="text-xl font-bold text-green-700">5</p>
<p className="text-xs text-green-600">+25%</p>
</div>
</div>
<div className="h-48 bg-gray-100 rounded-lg flex items-center justify-center">
<p className="text-gray-500"></p>
</div>
</div>
</CardContent>
</Card>
</div>
</TabsContent>
{/* 团队管理 */}
<TabsContent value="team" className="mt-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle> ({teamMembers.length})</CardTitle>
<Button variant="outline" size="sm">
<Users className="w-4 h-4 mr-2" />
</Button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{teamMembers.map((member) => (
<div key={member.id} className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 transition-colors">
<div className="flex items-center gap-3">
<Avatar className="w-10 h-10">
<AvatarImage src={member.avatarUrl} />
<AvatarFallback>{member.avatar}</AvatarFallback>
</Avatar>
<div>
<p className="font-medium">{member.name}</p>
<p className="text-sm text-gray-600">{member.level}</p>
</div>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="font-bold">{member.totalOrders}</p>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="font-bold text-blue-600">{member.monthlyOrders}</p>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="font-bold text-green-600">¥{member.commission.toFixed(2)}</p>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="text-sm">{member.joinTime}</p>
</div>
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${member.status === 'active' ? 'bg-green-500' : 'bg-gray-400'}`} />
<span className="text-sm">{member.status === 'active' ? '活跃' : '离线'}</span>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
{/* 素材库 */}
<TabsContent value="materials" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6">
{materials.map((material) => (
<Card key={material.id} className="overflow-hidden hover:shadow-lg transition-shadow">
<div className="aspect-video bg-gray-100">
<img
src={material.image}
alt={material.title}
className="w-full h-full object-cover"
/>
</div>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<h3 className="font-semibold">{material.title}</h3>
<Badge variant="outline">{material.category}</Badge>
</div>
<p className="text-sm text-gray-600 mb-3 line-clamp-2">{material.content}</p>
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-1">
<Star className="w-4 h-4 text-yellow-500" />
<span className="text-sm">{material.rating}</span>
</div>
<span className="text-sm text-gray-500">使 {material.usage} </span>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant="outline"
className="flex-1"
onClick={() => copyMaterial(material.content)}
>
<Copy className="w-4 h-4 mr-1" />
</Button>
<Button size="sm" variant="outline" className="flex-1">
<Download className="w-4 h-4 mr-1" />
</Button>
<Button size="sm" variant="outline">
<Share2 className="w-4 h-4" />
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
{/* 任务体系 */}
<TabsContent value="tasks" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{tasks.map((task) => (
<Card key={task.id} className={`relative ${task.status === 'completed' ? 'bg-green-50 border-green-200' : ''}`}>
<CardContent className="p-6">
<div className="flex items-center gap-3 mb-4">
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${
task.status === 'completed' ? 'bg-green-100' : `${task.color}-100`
}`}>
{task.status === 'completed' ? (
<Award className="w-5 h-5 text-green-600" />
) : (
<task.icon className={`w-5 h-5 text-${task.color}-600`} />
)}
</div>
<div className="flex-1">
<h3 className="font-semibold">{task.title}</h3>
<p className="text-sm text-gray-600">{task.description}</p>
</div>
<Badge variant={task.status === 'completed' ? 'default' : 'secondary'}>
{task.status === 'completed' ? '已完成' : '进行中'}
</Badge>
</div>
<div className="space-y-2 mb-4">
<div className="flex items-center justify-between text-sm">
<span></span>
<span className="font-medium">{task.progress}/{task.target}</span>
</div>
<Progress
value={(task.progress / task.target) * 100}
className="h-2"
/>
</div>
<div className="p-3 bg-yellow-50 rounded-lg">
<div className="flex items-center gap-2">
<Gift className="w-4 h-4 text-yellow-600" />
<span className="text-sm font-medium text-yellow-800">{task.reward}</span>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
</Tabs>
</div>
{/* 小程序风格底部导航栏 */}
<nav className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-100 safe-area-inset-bottom">
<div className="flex items-center justify-around py-2">
<a href="/" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<Home className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/group" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<ShoppingCart className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/distribution" className="flex flex-col items-center gap-1 py-1 text-red-500 active:bg-red-50 rounded-lg px-3">
<TrendingUp className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/profile" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<Users className="w-5 h-5" />
<span className="text-xs"></span>
</a>
</div>
</nav>
</div>
)
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

11
src/app/globals.css Normal file
View File

@ -0,0 +1,11 @@
@import "tailwindcss";
@layer base {
* {
border-color: hsl(var(--border));
}
body {
background-color: hsl(var(--background));
color: hsl(var(--foreground));
}
}

612
src/app/group/[id]/page.tsx Normal file
View File

@ -0,0 +1,612 @@
'use client'
import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import {
Package,
Users,
Clock,
Calendar,
CheckCircle,
Truck,
Shield,
Award,
ChevronRight,
ArrowLeft,
Share2,
Heart,
MessageCircle,
Star,
MapPin,
Phone,
Mail,
Camera,
FileText,
Box,
TrendingUp,
Zap,
Target,
Crown,
Bookmark,
Send,
Gift
} from 'lucide-react'
import { showSuccessToast, showErrorToast, showShareToast } from '@/lib/toast-utils'
interface GroupDetails {
id: string
title: string
description: string
image: string
originalPrice: number
groupPrice: number
groupSize: number
currentMembers: number
startTime: string
endTime: string
status: 'in_progress' | 'completed' | 'failed'
host: {
name: string
avatar: string
phone: string
email: string
rating: number
}
product: {
name: string
description: string
images: string[]
specifications: Record<string, string>
origin: string
brand: string
}
members: Array<{
id: string
name: string
avatar: string
joinTime: string
paymentStatus: 'paid' | 'pending' | 'failed'
shippingStatus: 'pending' | 'shipped' | 'delivered'
address: string
}>
progress: {
stage: 'gathering' | 'purchasing' | 'authenticating' | 'packaging' | 'shipping' | 'completed'
stages: Array<{
name: string
status: 'completed' | 'in_progress' | 'pending'
time?: string
details?: string
}>
}
timeline: Array<{
id: string
title: string
description: string
time: string
type: 'info' | 'success' | 'warning'
}>
statistics: {
views: number
shares: number
likes: number
comments: number
}
}
export default function GroupDetailsPage() {
const params = useParams()
const router = useRouter()
const [groupDetails, setGroupDetails] = useState<GroupDetails | null>(null)
const [liked, setLiked] = useState(false)
const [bookmarked, setBookmarked] = useState(false)
const [showGroupDialog, setShowGroupDialog] = useState(false)
// 模拟拼团详情数据
useEffect(() => {
const mockData: GroupDetails = {
id: params.id as string,
title: '法国进口玫瑰香水拼团',
description: '正宗法国格拉斯玫瑰精油,纯天然提取,持久留香',
image: '/api/placeholder/400/400',
originalPrice: 399,
groupPrice: 259,
groupSize: 5,
currentMembers: 4,
startTime: '2025-03-26 10:00',
endTime: '2025-04-02 22:00',
status: 'in_progress',
host: {
name: '香香公主',
avatar: '香',
phone: '138****8888',
email: 'xiangxiang@example.com',
rating: 4.9
},
product: {
name: '法国格拉斯玫瑰香水',
description: '采用法国格拉斯地区五月玫瑰制成每瓶含有1000朵玫瑰精华',
images: ['/api/placeholder/400/400', '/api/placeholder/400/400'],
specifications: {
'容量': '50ml',
'香调': '花香调',
'浓度': 'EDP',
'保质期': '3年'
},
origin: '法国格拉斯',
brand: '法国玫瑰庄园'
},
members: [
{
id: '1',
name: '香香公主',
avatar: '香',
joinTime: '2025-03-26 10:00',
paymentStatus: 'paid',
shippingStatus: 'pending',
address: '北京市朝阳区xxx街道'
},
{
id: '2',
name: '花仙子',
avatar: '花',
joinTime: '2025-03-26 14:30',
paymentStatus: 'paid',
shippingStatus: 'pending',
address: '上海市浦东新区xxx路'
},
{
id: '3',
name: '小仙女',
avatar: '仙',
joinTime: '2025-03-27 09:15',
paymentStatus: 'paid',
shippingStatus: 'pending',
address: '广州市天河区xxx大道'
},
{
id: '4',
name: '美美哒',
avatar: '美',
joinTime: '2025-03-27 16:45',
paymentStatus: 'paid',
shippingStatus: 'pending',
address: '深圳市南山区xxx街'
}
],
progress: {
stage: 'purchasing',
stages: [
{
name: '拼团进行中',
status: 'completed',
time: '2025-03-26 10:00',
details: '拼团成功开始'
},
{
name: '采购中',
status: 'in_progress',
time: '2025-03-28 10:00',
details: '正在向法国供应商下单采购'
},
{
name: '真品验证',
status: 'pending',
details: '到货后进行真品验证'
},
{
name: '分装中',
status: 'pending',
details: '专业分装员进行分装'
},
{
name: '发货中',
status: 'pending',
details: '逐个发货给成员'
}
]
},
timeline: [
{
id: '1',
title: '拼团创建',
description: '香香公主创建了拼团活动',
time: '2025-03-26 10:00',
type: 'info'
},
{
id: '2',
title: '花仙子加入',
description: '第2位成员加入拼团',
time: '2025-03-26 14:30',
type: 'success'
},
{
id: '3',
title: '小仙女加入',
description: '第3位成员加入拼团',
time: '2025-03-27 09:15',
type: 'success'
},
{
id: '4',
title: '美美哒加入',
description: '第4位成员加入拼团',
time: '2025-03-27 16:45',
type: 'success'
},
{
id: '5',
title: '开始采购',
description: '拼团成功,开始向供应商采购',
time: '2025-03-28 10:00',
type: 'info'
}
],
statistics: {
views: 1258,
shares: 45,
likes: 89,
comments: 23
}
}
setGroupDetails(mockData)
}, [params.id])
const handleShare = () => {
if (navigator.share) {
navigator.share({
title: groupDetails?.title,
text: `来看看这个超棒的拼团活动!`,
url: window.location.href
})
} else {
navigator.clipboard.writeText(window.location.href)
showSuccessToast('分享链接已复制')
}
showShareToast()
}
const handleLike = () => {
setLiked(!liked)
showSuccessToast(liked ? '已取消点赞' : '已点赞')
}
const handleJoinGroup = () => {
showSuccessToast('参团申请已提交,等待团长审核')
}
const handleBookmark = () => {
setBookmarked(!bookmarked)
showSuccessToast(bookmarked ? '已取消收藏' : '已收藏')
}
const getStatusColor = (status: string) => {
switch (status) {
case 'completed':
return 'bg-green-500'
case 'in_progress':
return 'bg-blue-500'
case 'pending':
return 'bg-gray-400'
case 'failed':
return 'bg-red-500'
default:
return 'bg-gray-400'
}
}
const getStatusText = (status: string) => {
switch (status) {
case 'completed':
return '已完成'
case 'in_progress':
return '进行中'
case 'pending':
return '待处理'
case 'failed':
return '已失败'
default:
return '未知'
}
}
if (!groupDetails) {
return (
<div className="min-h-screen bg-white flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-500 mx-auto mb-4"></div>
<p className="text-gray-500">...</p>
</div>
</div>
)
}
return (
<div className="min-h-screen bg-gray-50 pb-20">
{/* 顶部导航 */}
<div className="sticky top-0 z-50 bg-white border-b border-gray-200">
<div className="flex items-center justify-between px-4 py-3">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" className="p-2" onClick={() => router.back()}>
<ArrowLeft className="w-5 h-5" />
</Button>
<h1 className="text-lg font-semibold"></h1>
</div>
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" className="p-2" onClick={handleLike}>
<Heart className={`w-5 h-5 ${liked ? 'fill-red-500 text-red-500' : ''}`} />
</Button>
<Button variant="ghost" size="sm" className="p-2" onClick={handleBookmark}>
<Bookmark className={`w-5 h-5 ${bookmarked ? 'fill-yellow-500 text-yellow-500' : ''}`} />
</Button>
<Button variant="ghost" size="sm" className="p-2" onClick={handleShare}>
<Share2 className="w-5 h-5" />
</Button>
</div>
</div>
</div>
<div className="max-w-lg mx-auto space-y-4 p-4">
{/* 商品图片和基本信息 */}
<Card className="border-0 shadow-xl rounded-2xl overflow-hidden">
<div className="relative">
<img
src={groupDetails.image}
alt={groupDetails.title}
className="w-full h-72 object-cover"
/>
<div className="absolute top-4 left-4">
<Badge className="bg-gradient-to-r from-red-500 to-pink-500 text-white shadow-lg">
{getStatusText(groupDetails.status)}
</Badge>
</div>
<div className="absolute bottom-4 right-4">
<div className="flex items-center gap-2 bg-black/50 backdrop-blur-sm rounded-full px-3 py-1">
<Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
<span className="text-white text-sm font-medium">{groupDetails.host.rating}</span>
</div>
</div>
</div>
<CardContent className="p-6">
<h2 className="text-xl font-bold mb-3">{groupDetails.title}</h2>
<p className="text-gray-600 text-sm mb-4 leading-relaxed">{groupDetails.description}</p>
<div className="flex items-baseline gap-3 mb-6">
<span className="text-3xl font-bold text-red-500">¥{groupDetails.groupPrice}</span>
<span className="text-lg text-gray-400 line-through">¥{groupDetails.originalPrice}</span>
<Badge variant="secondary" className="bg-red-50 text-red-600 border-red-200">
¥{groupDetails.originalPrice - groupDetails.groupPrice}
</Badge>
</div>
<div className="grid grid-cols-2 gap-4 text-sm">
<div className="flex items-center gap-2 p-3 bg-purple-50 rounded-lg">
<Users className="w-4 h-4 text-purple-600" />
<span className="text-purple-900 font-medium">{groupDetails.currentMembers}/{groupDetails.groupSize}</span>
</div>
<div className="flex items-center gap-2 p-3 bg-blue-50 rounded-lg">
<MapPin className="w-4 h-4 text-blue-600" />
<span className="text-blue-900 font-medium">{groupDetails.product.origin}</span>
</div>
</div>
</CardContent>
</Card>
{/* 拼团进度 - 整合了时间信息 */}
<Card className="border-0 shadow-sm">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<TrendingUp className="w-5 h-5 text-purple-500" />
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* 时间信息整合到进度卡片中 */}
<div className="bg-purple-50 p-3 rounded-lg">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Calendar className="w-4 h-4 text-purple-600" />
<span className="text-sm font-medium text-purple-900"></span>
</div>
<Badge variant="outline" className="text-purple-600 border-purple-200">
{groupDetails.currentMembers >= groupDetails.groupSize ? '已成团' : '进行中'}
</Badge>
</div>
<div className="grid grid-cols-2 gap-2 text-sm">
<div>
<span className="text-gray-500"></span>
<span className="text-purple-900">{groupDetails.startTime}</span>
</div>
<div>
<span className="text-gray-500"></span>
<span className="text-purple-900">{groupDetails.endTime}</span>
</div>
</div>
</div>
{/* 进度条 */}
<div>
<div className="flex justify-between text-sm mb-2">
<span></span>
<span className="font-medium">{groupDetails.currentMembers}/{groupDetails.groupSize}</span>
</div>
<Progress value={(groupDetails.currentMembers / groupDetails.groupSize) * 100} className="h-2" />
</div>
{/* 阶段进度 */}
<div className="space-y-3">
{groupDetails.progress.stages.map((stage, index) => (
<div key={index} className="flex items-center gap-3">
<div className={`w-3 h-3 rounded-full ${getStatusColor(stage.status)}`} />
<div className="flex-1">
<div className="flex items-center justify-between">
<span className="text-sm font-medium">{stage.name}</span>
{stage.time && (
<span className="text-xs text-gray-500">{stage.time}</span>
)}
</div>
{stage.details && (
<p className="text-xs text-gray-500 mt-1">{stage.details}</p>
)}
</div>
{stage.status === 'completed' && (
<CheckCircle className="w-4 h-4 text-green-500" />
)}
{stage.status === 'in_progress' && (
<div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
)}
</div>
))}
</div>
</CardContent>
</Card>
{/* 拼团成员 */}
<Card className="border-0 shadow-sm">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Users className="w-5 h-5 text-blue-500" />
({groupDetails.members.length})
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
{groupDetails.members.map((member) => (
<div key={member.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
<Avatar className="w-10 h-10">
<AvatarFallback className="bg-gradient-to-r from-blue-500 to-purple-500 text-white text-sm">
{member.avatar}
</AvatarFallback>
</Avatar>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="font-medium text-sm">{member.name}</span>
{member.id === '1' && (
<Badge variant="outline" className="text-xs"></Badge>
)}
</div>
<div className="flex items-center gap-3 text-xs text-gray-500 mt-1">
<span>{member.joinTime}</span>
<span></span>
<span className={`flex items-center gap-1 ${
member.paymentStatus === 'paid' ? 'text-green-600' : 'text-orange-600'
}`}>
{member.paymentStatus === 'paid' ? '已付款' : '待付款'}
</span>
</div>
</div>
<ChevronRight className="w-4 h-4 text-gray-400" />
</div>
))}
</div>
{groupDetails.currentMembers < groupDetails.groupSize && (
<div className="mt-4 p-3 border-2 border-dashed border-gray-300 rounded-lg text-center">
<p className="text-sm text-gray-500 mb-2">
{groupDetails.groupSize - groupDetails.currentMembers}
</p>
<Button className="w-full bg-gradient-to-r from-purple-500 to-pink-500" onClick={handleJoinGroup}>
</Button>
</div>
)}
</CardContent>
</Card>
{/* 时间线和统计 */}
<Card className="border-0 shadow-sm">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Clock className="w-5 h-5 text-green-500" />
线
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
{groupDetails.timeline.map((item) => (
<div key={item.id} className="flex gap-3">
<div className={`w-2 h-2 rounded-full mt-2 ${
item.type === 'success' ? 'bg-green-500' :
item.type === 'warning' ? 'bg-yellow-500' : 'bg-blue-500'
}`} />
<div className="flex-1">
<div className="flex items-center justify-between">
<span className="text-sm font-medium">{item.title}</span>
<span className="text-xs text-gray-500">{item.time}</span>
</div>
<p className="text-xs text-gray-600 mt-1">{item.description}</p>
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* 活动数据统计 */}
<Card className="border-0 shadow-lg rounded-2xl">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<TrendingUp className="w-5 h-5 text-orange-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4">
<div className="text-center p-4 bg-gradient-to-br from-purple-50 to-pink-50 rounded-xl">
<div className="text-2xl font-bold text-purple-600 mb-1">{groupDetails.statistics.views}</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-blue-50 to-cyan-50 rounded-xl">
<div className="text-2xl font-bold text-blue-600 mb-1">{groupDetails.statistics.shares}</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-red-50 to-orange-50 rounded-xl">
<div className="text-2xl font-bold text-red-600 mb-1">{groupDetails.statistics.likes}</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="text-center p-4 bg-gradient-to-br from-green-50 to-emerald-50 rounded-xl">
<div className="text-2xl font-bold text-green-600 mb-1">{groupDetails.statistics.comments}</div>
<div className="text-sm text-gray-600"></div>
</div>
</div>
</CardContent>
</Card>
</div>
{/* 底部操作栏 */}
<div className="fixed bottom-16 left-0 right-0 bg-white border-t border-gray-200 shadow-lg z-40">
<div className="max-w-lg mx-auto px-4 py-3">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" className="p-2 rounded-full" onClick={handleLike}>
<Heart className={`w-5 h-5 ${liked ? 'fill-red-500 text-red-500' : 'text-gray-500'}`} />
</Button>
<Button variant="ghost" size="sm" className="p-2 rounded-full" onClick={handleShare}>
<Share2 className="w-5 h-5 text-gray-500" />
</Button>
<Button variant="ghost" size="sm" className="p-2 rounded-full">
<MessageCircle className="w-5 h-5 text-gray-500" />
</Button>
</div>
<Button
className="flex-1 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-medium py-3 rounded-full shadow-lg transform transition-all duration-200 hover:scale-105"
onClick={handleJoinGroup}
>
<Gift className="w-5 h-5 mr-2" />
</Button>
</div>
</div>
</div>
{/* 底部导航栏 */}
</div>
)
}

359
src/app/group/page.tsx Normal file
View File

@ -0,0 +1,359 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import {
Users,
Clock,
Heart,
Search,
Star,
ShoppingCart,
TrendingUp,
Home,
Crown,
Gift,
Zap
} from 'lucide-react'
export default function GroupListPage() {
const [activeTab, setActiveTab] = useState('all')
const [likedGroups, setLikedGroups] = useState<string[]>([])
// 模拟拼团数据
const groupBuys = [
{
id: '1',
title: '3人拼团 玫瑰香水盲盒',
description: '经典玫瑰香调,优雅女神范',
image: '/api/placeholder/300/200',
originalPrice: 199,
groupPrice: 139,
groupSize: 3,
currentMembers: 2,
timeLeft: '2小时23分',
status: 'active',
host: {
name: '香香公主',
avatar: '香',
rating: 4.9
},
category: '香水',
tags: ['热门', '限时']
},
{
id: '2',
title: '5人拼团 薰衣草精油套装',
description: '纯天然薰衣草精油,助眠神器',
image: '/api/placeholder/300/200',
originalPrice: 299,
groupPrice: 199,
groupSize: 5,
currentMembers: 3,
timeLeft: '1天5小时',
status: 'active',
host: {
name: '精油达人',
avatar: '精',
rating: 4.8
},
category: '精油',
tags: ['新品']
},
{
id: '3',
title: '2人拼团 茉莉香氛蜡烛',
description: '手工制作,天然大豆蜡',
image: '/api/placeholder/300/200',
originalPrice: 89,
groupPrice: 59,
groupSize: 2,
currentMembers: 1,
timeLeft: '6小时12分',
status: 'active',
host: {
name: '蜡烛工坊',
avatar: '蜡',
rating: 4.7
},
category: '香薰',
tags: ['手工', '天然']
},
{
id: '4',
title: '4人拼团 小样体验包',
description: '10款热门香水小样超值体验',
image: '/api/placeholder/300/200',
originalPrice: 99,
groupPrice: 29,
groupSize: 4,
currentMembers: 4,
timeLeft: '已成团',
status: 'success',
host: {
name: '小样控',
avatar: '样',
rating: 4.9
},
category: '小样',
tags: ['超值', '体验']
},
{
id: '5',
title: '3人拼团 沉香木手串',
description: '天然沉香木,淡雅香韵',
image: '/api/placeholder/300/200',
originalPrice: 399,
groupPrice: 299,
groupSize: 3,
currentMembers: 1,
timeLeft: '3天2小时',
status: 'active',
host: {
name: '香木匠人',
avatar: '木',
rating: 4.6
},
category: '香木',
tags: ['天然', '收藏']
}
]
const handleLike = (groupId: string) => {
setLikedGroups(prev =>
prev.includes(groupId)
? prev.filter(id => id !== groupId)
: [...prev, groupId]
)
}
const getFilteredGroups = () => {
switch (activeTab) {
case 'active':
return groupBuys.filter(group => group.status === 'active')
case 'success':
return groupBuys.filter(group => group.status === 'success')
case 'hot':
return groupBuys.filter(group => group.tags.includes('热门'))
default:
return groupBuys
}
}
const getStatusBadge = (group: any) => {
if (group.status === 'success') {
return <Badge className="bg-green-500 text-white text-xs px-2 py-1"></Badge>
}
if (group.currentMembers === group.groupSize - 1) {
return <Badge className="bg-orange-500 text-white text-xs px-2 py-1">1</Badge>
}
return <Badge className="bg-red-500 text-white text-xs px-2 py-1"></Badge>
}
return (
<div className="min-h-screen bg-gray-50">
{/* 小程序风格顶部导航 */}
<div className="sticky top-0 z-50 bg-white border-b border-gray-100">
<div className="px-4 py-3">
<div className="flex items-center justify-between">
<h1 className="text-lg font-bold text-gray-800"></h1>
<div className="flex items-center gap-2">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<input
type="text"
placeholder="搜索商品"
className="w-48 pl-10 pr-4 py-2 text-sm bg-gray-100 rounded-full focus:outline-none focus:bg-white focus:ring-1 focus:ring-purple-300"
/>
</div>
</div>
</div>
</div>
</div>
<div className="px-4 pb-20">
{/* 小程序风格统计卡片 */}
<div className="grid grid-cols-3 gap-3 py-4">
<div className="bg-gradient-to-br from-red-400 to-red-500 text-white p-3 rounded-xl text-center shadow-sm">
<div className="text-xl font-bold">156</div>
<div className="text-xs opacity-90"></div>
</div>
<div className="bg-gradient-to-br from-green-400 to-green-500 text-white p-3 rounded-xl text-center shadow-sm">
<div className="text-xl font-bold">89</div>
<div className="text-xs opacity-90"></div>
</div>
<div className="bg-gradient-to-br from-orange-400 to-orange-500 text-white p-3 rounded-xl text-center shadow-sm">
<div className="text-xl font-bold">2.3k</div>
<div className="text-xs opacity-90"></div>
</div>
</div>
{/* 小程序风格分类标签 */}
<div className="flex gap-2 mb-4 overflow-x-auto scrollbar-hide">
{[
{ key: 'all', label: '全部' },
{ key: 'active', label: '进行中' },
{ key: 'hot', label: '热门' },
{ key: 'success', label: '已成团' }
].map((tab) => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-all ${
activeTab === tab.key
? 'bg-red-500 text-white shadow-md'
: 'bg-white text-gray-600 border border-gray-200'
}`}
>
{tab.label}
</button>
))}
</div>
{/* 拼团商品列表 - 小程序风格 */}
<div className="space-y-3">
{getFilteredGroups().map((group) => (
<Card key={group.id} className="overflow-hidden bg-white rounded-xl shadow-sm border-0">
<div className="flex">
{/* 商品图片 */}
<div className="relative w-28 h-28 flex-shrink-0">
<img
src={group.image}
alt={group.title}
className="w-full h-full object-cover rounded-l-xl"
/>
<div className="absolute top-2 left-2">
{getStatusBadge(group)}
</div>
{group.tags.map((tag, index) => (
<Badge
key={index}
className="absolute bottom-2 left-2 bg-black/60 text-white text-xs px-1.5 py-0.5"
>
{tag}
</Badge>
))}
</div>
{/* 商品信息 */}
<div className="flex-1 p-3">
<div className="flex justify-between items-start mb-2">
<h3 className="font-medium text-sm text-gray-800 line-clamp-2 flex-1 mr-2">
{group.title}
</h3>
<button
onClick={() => handleLike(group.id)}
className="p-1"
>
<Heart className={`w-4 h-4 ${likedGroups.includes(group.id) ? 'fill-red-500 text-red-500' : 'text-gray-400'}`} />
</button>
</div>
{/* 价格信息 */}
<div className="flex items-baseline gap-2 mb-2">
<span className="text-lg font-bold text-red-500">¥{group.groupPrice}</span>
<span className="text-xs text-gray-400 line-through">¥{group.originalPrice}</span>
</div>
{/* 拼团进度 */}
<div className="mb-2">
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-1">
<Users className="w-3 h-3 text-red-500" />
<span className="text-xs text-gray-600"></span>
</div>
<span className="text-xs font-medium text-red-500">
{group.currentMembers}/{group.groupSize}
</span>
</div>
<Progress
value={(group.currentMembers / group.groupSize) * 100}
className="h-1.5"
/>
</div>
{/* 底部信息 */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-1">
<div className="relative">
<Avatar className="w-4 h-4">
<AvatarFallback className="text-xs bg-gray-200">{group.host.avatar}</AvatarFallback>
</Avatar>
<Crown className="w-2 h-2 text-yellow-500 absolute -top-0.5 -right-0.5" />
</div>
<span className="text-xs text-gray-500">{group.host.name}</span>
<Star className="w-2.5 h-2.5 text-yellow-500 fill-current" />
<span className="text-xs text-gray-500">{group.host.rating}</span>
</div>
<div className="flex items-center gap-1 text-orange-500">
<Clock className="w-3 h-3" />
<span className="text-xs">{group.timeLeft}</span>
</div>
</div>
</div>
</div>
{/* 操作按钮 */}
<div className="px-3 pb-3">
<Link href={`/group/${group.id}`} className="block">
<Button
className="w-full h-8 bg-gradient-to-r from-red-400 to-red-500 hover:from-red-500 hover:to-red-600 text-white text-sm rounded-full"
disabled={group.status === 'success'}
>
{group.status === 'success' ? (
<>
<Gift className="w-3 h-3 mr-1" />
</>
) : (
<>
<Users className="w-3 h-3 mr-1" />
</>
)}
</Button>
</Link>
</div>
</Card>
))}
</div>
{/* 空状态 */}
{getFilteredGroups().length === 0 && (
<div className="text-center py-12">
<Users className="w-16 h-16 text-gray-300 mx-auto mb-4" />
<h3 className="text-base font-medium text-gray-600 mb-2"></h3>
<p className="text-sm text-gray-500"></p>
</div>
)}
</div>
{/* 小程序风格底部导航栏 */}
<nav className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-100 safe-area-inset-bottom">
<div className="flex items-center justify-around py-2">
<Link href="/" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<Home className="h-5 w-5" />
<span className="text-xs"></span>
</Link>
<Link href="/group" className="flex flex-col items-center gap-1 py-1 text-red-500 active:bg-red-50 rounded-lg px-3">
<ShoppingCart className="h-5 w-5" />
<span className="text-xs"></span>
</Link>
<Link href="/distribution" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<TrendingUp className="h-5 w-5" />
<span className="text-xs"></span>
</Link>
<Link href="/profile" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<Users className="h-5 w-5" />
<span className="text-xs"></span>
</Link>
</div>
</nav>
</div>
)
}

54
src/app/layout.tsx Normal file
View File

@ -0,0 +1,54 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Toaster } from "@/components/ui/toaster";
import BottomNavigation from "@/components/bottom-navigation";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Z.ai Code Scaffold - AI-Powered Development",
description: "Modern Next.js scaffold optimized for AI-powered development with Z.ai. Built with TypeScript, Tailwind CSS, and shadcn/ui.",
keywords: ["Z.ai", "Next.js", "TypeScript", "Tailwind CSS", "shadcn/ui", "AI development", "React"],
authors: [{ name: "Z.ai Team" }],
openGraph: {
title: "Z.ai Code Scaffold",
description: "AI-powered development with modern React stack",
url: "https://chat.z.ai",
siteName: "Z.ai",
type: "website",
},
twitter: {
card: "summary_large_image",
title: "Z.ai Code Scaffold",
description: "AI-powered development with modern React stack",
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-background text-foreground pb-16`}
>
<div className="min-h-screen pb-16">
{children}
</div>
<BottomNavigation />
<Toaster />
</body>
</html>
);
}

385
src/app/page.tsx Normal file
View File

@ -0,0 +1,385 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { ProductCard } from '@/components/product-card'
import { GroupCard } from '@/components/group-card'
import { ProductCardSkeleton, GroupCardSkeleton } from '@/components/loading-states'
import { FadeIn, SlideIn, StaggerContainer, StaggerItem } from '@/components/animations'
import {
Heart,
Send,
Search,
Sparkles,
TrendingUp,
Grid3X3,
List,
Filter,
Clock
} from 'lucide-react'
import { showSuccessToast, showErrorToast, showLikeToast, showShareToast } from '@/lib/toast-utils'
export default function HomePage() {
const router = useRouter()
const [likedPosts, setLikedPosts] = useState<string[]>([])
const [bookmarkedItems, setBookmarkedItems] = useState<string[]>([])
const [joinedGroups, setJoinedGroups] = useState<string[]>([])
const [showGroupDialog, setShowGroupDialog] = useState(false)
const [viewMode, setViewMode] = useState<'grid' | 'list'>('list')
const [activeTab, setActiveTab] = useState<'products' | 'groups'>('products')
const [isLoading, setIsLoading] = useState(true)
const [isRefreshing, setIsRefreshing] = useState(false)
// 模拟初始加载
useEffect(() => {
const timer = setTimeout(() => {
setIsLoading(false)
}, 1500)
return () => clearTimeout(timer)
}, [])
// 模拟刷新数据
const handleRefresh = async () => {
setIsRefreshing(true)
// 模拟API调用
await new Promise(resolve => setTimeout(resolve, 1000))
setIsRefreshing(false)
showSuccessToast('数据已更新')
}
// 切换标签页时的动画效果
const handleTabChange = (tab: 'products' | 'groups') => {
if (tab !== activeTab) {
setIsRefreshing(true)
setTimeout(() => {
setActiveTab(tab)
setIsRefreshing(false)
}, 300)
}
}
const featuredProducts = [
{
id: '1',
name: '玫瑰香水盲盒',
image: '/api/placeholder/400/400',
price: 139,
originalPrice: 199,
discount: '7折',
rating: 4.8,
reviews: 234,
likes: 567,
comments: 89,
description: '经典玫瑰香调优雅女神范持久留香8小时',
tags: ['热销', '限量'],
stock: 15,
category: 'floral',
isHot: true,
isNew: false
},
{
id: '2',
name: '薰衣草助眠香氛',
image: '/api/placeholder/400/400',
price: 89,
originalPrice: 129,
discount: '69折',
rating: 4.6,
reviews: 156,
likes: 423,
comments: 67,
description: '天然薰衣草精油,助眠好伴侣,舒缓身心',
tags: ['新品', '助眠'],
stock: 8,
category: 'herbal',
isHot: false,
isNew: true
}
]
// 优化后的拼团活动数据
const groupBuyingActivities = [
{
id: '1',
title: '3人拼团 玫瑰香水',
image: '/api/placeholder/400/400',
originalPrice: 199,
groupPrice: 139,
groupSize: 3,
currentMembers: 2,
timeLeft: '2小时23分',
host: '香香公主',
hostAvatar: '香',
likes: 234,
comments: 45,
isHot: true,
urgency: 'high' as const
},
{
id: '2',
title: '5人拼团 薰衣草套装',
image: '/api/placeholder/400/400',
originalPrice: 299,
groupPrice: 199,
groupSize: 5,
currentMembers: 4,
timeLeft: '5小时12分',
host: '花仙子',
hostAvatar: '花',
likes: 189,
comments: 32,
isHot: false,
urgency: 'medium' as const
}
]
const toggleLike = (postId: string) => {
setLikedPosts(prev =>
prev.includes(postId)
? prev.filter(id => id !== postId)
: [...prev, postId]
)
showLikeToast()
}
const toggleBookmark = (itemId: string) => {
setBookmarkedItems(prev =>
prev.includes(itemId)
? prev.filter(id => id !== itemId)
: [...prev, itemId]
)
showSuccessToast(bookmarkedItems.includes(itemId) ? '已取消收藏' : '已添加收藏')
}
const joinGroup = (groupId: string) => {
if (!joinedGroups.includes(groupId)) {
setJoinedGroups(prev => [...prev, groupId])
showSuccessToast('参团成功!等待其他成员加入')
}
setShowGroupDialog(false)
}
const viewGroupDetails = (groupId: string) => {
router.push(`/group/${groupId}`)
}
const shareContent = (title: string) => {
if (navigator.share) {
navigator.share({
title: title,
text: `来看看这个超棒的香氛产品!`,
})
} else {
navigator.clipboard.writeText(`来看看这个超棒的香氛产品:${title}`)
showSuccessToast('分享链接已复制')
}
showShareToast()
}
const handlePurchase = (productId: string) => {
showSuccessToast('正在跳转到购买页面...')
// 这里可以添加购买逻辑
}
return (
<div className="min-h-screen bg-gradient-to-br from-purple-50 via-white to-pink-50">
{/* 优化后的顶部导航栏 */}
<FadeIn>
<div className="sticky top-0 z-50 bg-white/80 backdrop-blur-md border-b border-gray-200/50 shadow-sm">
<div className="px-4 py-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<SlideIn direction="left">
<div className="flex items-center gap-2">
<Sparkles className="w-6 h-6 text-purple-600" />
<h1 className="text-xl font-bold bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent">
</h1>
</div>
</SlideIn>
</div>
<SlideIn direction="right">
<div className="flex items-center gap-3">
<Button
variant="ghost"
size="sm"
className="p-2 hover:bg-purple-50 transition-colors duration-200"
onClick={handleRefresh}
disabled={isRefreshing}
>
<Search className={`w-5 h-5 text-gray-600 ${isRefreshing ? 'animate-spin' : ''}`} />
</Button>
<Button variant="ghost" size="sm" className="p-2 hover:bg-purple-50 transition-colors duration-200">
<Heart className="w-5 h-5 text-gray-600" />
</Button>
<Button variant="ghost" size="sm" className="p-2 hover:bg-purple-50 transition-colors duration-200">
<Send className="w-5 h-5 text-gray-600" />
</Button>
</div>
</SlideIn>
</div>
</div>
</div>
</FadeIn>
{/* 主要内容 */}
<div className="pb-20">
{/* 标签切换和视图控制 */}
<div className="max-w-lg mx-auto px-4 py-6">
<SlideIn delay={0.2}>
<div className="flex items-center justify-between mb-6">
<div className="flex items-center bg-white rounded-2xl p-1 shadow-sm border border-gray-100">
<Button
variant={activeTab === 'products' ? 'default' : 'ghost'}
size="sm"
className={`px-6 py-2 rounded-xl transition-all duration-300 ${
activeTab === 'products'
? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white shadow-md transform scale-105'
: 'text-gray-600 hover:text-purple-600 hover:bg-purple-50'
}`}
onClick={() => handleTabChange('products')}
>
<TrendingUp className="w-4 h-4 mr-2" />
</Button>
<Button
variant={activeTab === 'groups' ? 'default' : 'ghost'}
size="sm"
className={`px-6 py-2 rounded-xl transition-all duration-300 ${
activeTab === 'groups'
? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white shadow-md transform scale-105'
: 'text-gray-600 hover:text-purple-600 hover:bg-purple-50'
}`}
onClick={() => handleTabChange('groups')}
>
<Heart className="w-4 h-4 mr-2" />
</Button>
</div>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className={`p-2 rounded-xl transition-all duration-200 ${
viewMode === 'grid'
? 'bg-purple-100 text-purple-600 transform scale-110'
: 'text-gray-400 hover:text-purple-600 hover:bg-purple-50'
}`}
onClick={() => setViewMode('grid')}
>
<Grid3X3 className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
className={`p-2 rounded-xl transition-all duration-200 ${
viewMode === 'list'
? 'bg-purple-100 text-purple-600 transform scale-110'
: 'text-gray-400 hover:text-purple-600 hover:bg-purple-50'
}`}
onClick={() => setViewMode('list')}
>
<List className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="p-2 rounded-xl text-gray-400 hover:text-purple-600 hover:bg-purple-50 transition-all duration-200"
>
<Filter className="w-4 h-4" />
</Button>
</div>
</div>
</SlideIn>
{/* 加载状态 */}
{isLoading && (
<StaggerContainer className={`space-y-6 ${viewMode === 'grid' ? 'grid grid-cols-2 gap-4 space-y-0' : ''}`}>
{Array.from({ length: 4 }).map((_, index) => (
<StaggerItem key={index}>
{activeTab === 'products' ? (
<ProductCardSkeleton variant={viewMode === 'grid' ? 'compact' : 'default'} />
) : (
<GroupCardSkeleton variant={viewMode === 'grid' ? 'compact' : 'default'} />
)}
</StaggerItem>
))}
</StaggerContainer>
)}
{/* 推荐产品区域 */}
{!isLoading && activeTab === 'products' && (
<StaggerContainer className={`space-y-6 ${viewMode === 'grid' ? 'grid grid-cols-2 gap-4 space-y-0' : ''}`}>
{featuredProducts.map((product, index) => (
<StaggerItem key={product.id}>
<ProductCard
product={product}
onLike={toggleLike}
onBookmark={toggleBookmark}
onShare={shareContent}
onPurchase={handlePurchase}
isLiked={likedPosts.includes(product.id)}
isBookmarked={bookmarkedItems.includes(product.id)}
variant={viewMode === 'grid' ? 'compact' : 'default'}
/>
</StaggerItem>
))}
</StaggerContainer>
)}
{/* 拼团活动区域 */}
{!isLoading && activeTab === 'groups' && (
<StaggerContainer className={`space-y-6 ${viewMode === 'grid' ? 'grid grid-cols-1 gap-6 space-y-0' : ''}`}>
{groupBuyingActivities.map((activity, index) => (
<StaggerItem key={activity.id}>
<GroupCard
activity={activity}
onLike={toggleLike}
onShare={shareContent}
onJoin={() => setShowGroupDialog(true)}
onViewDetails={viewGroupDetails}
isLiked={likedPosts.includes(activity.id)}
isJoined={joinedGroups.includes(activity.id)}
variant={viewMode === 'grid' ? 'compact' : 'default'}
/>
</StaggerItem>
))}
</StaggerContainer>
)}
</div>
</div>
{/* 参团确认对话框 */}
<Dialog open={showGroupDialog} onOpenChange={setShowGroupDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<div className="space-y-4">
<p className="text-sm text-gray-600">
</p>
<div className="flex gap-3">
<Button
variant="outline"
className="flex-1"
onClick={() => setShowGroupDialog(false)}
>
</Button>
<Button
className="flex-1 bg-gradient-to-r from-red-500 to-orange-500"
onClick={() => joinGroup('1')}
>
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
)
}

720
src/app/profile/page.tsx Normal file
View File

@ -0,0 +1,720 @@
'use client'
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import {
User,
Settings,
Package,
Heart,
Star,
Award,
Crown,
Gift,
ShoppingBag,
TrendingUp,
Calendar,
MapPin,
Phone,
Mail,
Edit,
Camera,
LogOut,
ChevronRight,
Shield,
CreditCard,
Bell,
HelpCircle,
FileText,
Zap,
Target,
Trophy,
Users,
ShoppingCart,
Share2,
Home
} from 'lucide-react'
export default function ProfilePage() {
const [activeTab, setActiveTab] = useState('overview')
const [showEditDialog, setShowEditDialog] = useState(false)
const [editForm, setEditForm] = useState({
name: '香香公主',
phone: '138****8888',
email: 'xiangxiang@example.com',
address: '上海市浦东新区张江高科技园区'
})
// 模拟用户数据
const userInfo = {
id: '1',
name: '香香公主',
avatar: '/api/placeholder/100/100',
phone: '138****8888',
email: 'xiangxiang@example.com',
address: '上海市浦东新区张江高科技园区',
joinDate: '2025-01-15',
membershipLevel: '品鉴会员',
points: 1280,
totalOrders: 23,
totalSpent: 2850.00,
favoriteCategory: '香水',
birthday: '1995-05-20'
}
const stats = {
thisMonthOrders: 5,
thisMonthSpent: 450.00,
savedMoney: 320.50,
sharedCount: 18,
teamSize: 8,
commissionEarned: 568.00
}
const orders = [
{
id: 'ORD20250402001',
date: '2025-04-02',
status: 'delivered',
total: 199.00,
items: [
{ name: '经典玫瑰香水30ml', quantity: 1, price: 199.00, image: '/api/placeholder/60/60' }
],
type: 'group_buy'
},
{
id: 'ORD20250401001',
date: '2025-04-01',
status: 'shipped',
total: 1.00,
items: [
{ name: '小样体验包', quantity: 1, price: 1.00, image: '/api/placeholder/60/60' }
],
type: 'flash_sale'
},
{
id: 'ORD20250328001',
date: '2025-03-28',
status: 'pending',
total: 299.00,
items: [
{ name: '薰衣草精油礼盒', quantity: 1, price: 299.00, image: '/api/placeholder/60/60' }
],
type: 'normal'
}
]
const favorites = [
{
id: '1',
name: '经典玫瑰香水30ml',
price: 199.00,
originalPrice: 299.00,
image: '/api/placeholder/150/150',
category: '香水',
rating: 4.8,
salesCount: 1250
},
{
id: '2',
name: '薰衣草精油礼盒',
price: 299.00,
originalPrice: 399.00,
image: '/api/placeholder/150/150',
category: '精油',
rating: 4.6,
salesCount: 890
},
{
id: '3',
name: '小样体验包',
price: 1.00,
originalPrice: 29.90,
image: '/api/placeholder/150/150',
category: '小样',
rating: 4.9,
salesCount: 2100
},
{
id: '4',
name: '茉莉香氛蜡烛',
price: 89.00,
originalPrice: 129.00,
image: '/api/placeholder/150/150',
category: '香薰',
rating: 4.7,
salesCount: 650
}
]
const achievements = [
{
id: '1',
name: '拼团达人',
description: '成功参与10次拼团',
icon: Users,
progress: 8,
target: 10,
unlocked: false,
reward: '专属优惠券'
},
{
id: '2',
name: '分享达人',
description: '分享商品20次',
icon: Share2,
progress: 18,
target: 20,
unlocked: false,
reward: '500积分'
},
{
id: '3',
name: '消费达人',
description: '累计消费满2000元',
icon: ShoppingBag,
progress: 2850,
target: 2000,
unlocked: true,
reward: 'VIP会员体验'
},
{
id: '4',
name: '评价达人',
description: '发表10条优质评价',
icon: Star,
progress: 6,
target: 10,
unlocked: false,
reward: '神秘礼品'
}
]
const addresses = [
{
id: '1',
name: '香香公主',
phone: '138****8888',
address: '上海市浦东新区张江高科技园区碧波路690号',
isDefault: true
},
{
id: '2',
name: '香香公主',
phone: '138****8888',
address: '上海市黄浦区南京东路100号',
isDefault: false
}
]
const handleSaveProfile = () => {
console.log('保存用户信息:', editForm)
setShowEditDialog(false)
}
const getStatusBadge = (status: string) => {
const statusMap = {
pending: { label: '待付款', className: 'bg-yellow-100 text-yellow-800' },
paid: { label: '待发货', className: 'bg-blue-100 text-blue-800' },
shipped: { label: '待收货', className: 'bg-purple-100 text-purple-800' },
delivered: { label: '已完成', className: 'bg-green-100 text-green-800' },
cancelled: { label: '已取消', className: 'bg-gray-100 text-gray-800' }
}
return statusMap[status as keyof typeof statusMap] || statusMap.pending
}
const getOrderTypeBadge = (type: string) => {
const typeMap = {
normal: { label: '普通订单', className: 'bg-gray-100 text-gray-800' },
group_buy: { label: '拼团订单', className: 'bg-purple-100 text-purple-800' },
flash_sale: { label: '秒杀订单', className: 'bg-red-100 text-red-800' },
subscription: { label: '订阅订单', className: 'bg-green-100 text-green-800' }
}
return typeMap[type as keyof typeof typeMap] || typeMap.normal
}
return (
<div className="min-h-screen bg-gray-50">
{/* Header */}
<div className="bg-gradient-to-r from-purple-600 to-pink-600 text-white">
<div className="max-w-6xl mx-auto px-4 py-8">
<div className="flex items-center gap-6">
<div className="relative">
<Avatar className="w-24 h-24">
<AvatarImage src={userInfo.avatar} />
<AvatarFallback className="text-2xl">{userInfo.name[0]}</AvatarFallback>
</Avatar>
<Button
size="sm"
className="absolute -bottom-2 -right-2 w-8 h-8 rounded-full bg-white text-purple-600 hover:bg-purple-50"
>
<Camera className="w-4 h-4" />
</Button>
</div>
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<h1 className="text-3xl font-bold">{userInfo.name}</h1>
<Badge className="bg-yellow-400 text-yellow-900">
<Crown className="w-3 h-3 mr-1" />
{userInfo.membershipLevel}
</Badge>
</div>
<div className="flex items-center gap-4 text-purple-100">
<div className="flex items-center gap-1">
<Calendar className="w-4 h-4" />
<span> {userInfo.joinDate}</span>
</div>
<div className="flex items-center gap-1">
<MapPin className="w-4 h-4" />
<span>{userInfo.address}</span>
</div>
</div>
</div>
<div className="text-right">
<Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
<DialogTrigger asChild>
<Button variant="outline" className="bg-white/20 border-white/30 text-white hover:bg-white/30">
<Edit className="w-4 h-4 mr-2" />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="name"></Label>
<Input
id="name"
value={editForm.name}
onChange={(e) => setEditForm({...editForm, name: e.target.value})}
/>
</div>
<div>
<Label htmlFor="phone"></Label>
<Input
id="phone"
value={editForm.phone}
onChange={(e) => setEditForm({...editForm, phone: e.target.value})}
/>
</div>
<div>
<Label htmlFor="email"></Label>
<Input
id="email"
value={editForm.email}
onChange={(e) => setEditForm({...editForm, email: e.target.value})}
/>
</div>
<div>
<Label htmlFor="address"></Label>
<Input
id="address"
value={editForm.address}
onChange={(e) => setEditForm({...editForm, address: e.target.value})}
/>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={() => setShowEditDialog(false)} className="flex-1">
</Button>
<Button onClick={handleSaveProfile} className="flex-1">
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
</div>
</div>
</div>
<div className="max-w-6xl mx-auto px-4 py-6">
{/* 统计卡片 */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
<Card className="text-center">
<CardContent className="p-4">
<Gift className="w-8 h-8 mx-auto mb-2 text-purple-500" />
<p className="text-2xl font-bold text-purple-600">{userInfo.points}</p>
<p className="text-sm text-gray-600"></p>
</CardContent>
</Card>
<Card className="text-center">
<CardContent className="p-4">
<ShoppingBag className="w-8 h-8 mx-auto mb-2 text-blue-500" />
<p className="text-2xl font-bold text-blue-600">{userInfo.totalOrders}</p>
<p className="text-sm text-gray-600"></p>
</CardContent>
</Card>
<Card className="text-center">
<CardContent className="p-4">
<TrendingUp className="w-8 h-8 mx-auto mb-2 text-green-500" />
<p className="text-2xl font-bold text-green-600">¥{stats.savedMoney.toFixed(0)}</p>
<p className="text-sm text-gray-600"></p>
</CardContent>
</Card>
<Card className="text-center">
<CardContent className="p-4">
<Users className="w-8 h-8 mx-auto mb-2 text-orange-500" />
<p className="text-2xl font-bold text-orange-600">{stats.teamSize}</p>
<p className="text-sm text-gray-600"></p>
</CardContent>
</Card>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-5">
<TabsTrigger value="overview"></TabsTrigger>
<TabsTrigger value="orders"></TabsTrigger>
<TabsTrigger value="favorites"></TabsTrigger>
<TabsTrigger value="achievements"></TabsTrigger>
<TabsTrigger value="settings"></TabsTrigger>
</TabsList>
{/* 概览 */}
<TabsContent value="overview" className="mt-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 本月数据 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ShoppingBag className="w-4 h-4 text-blue-500" />
<span></span>
</div>
<span className="font-bold">{stats.thisMonthOrders} </span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<TrendingUp className="w-4 h-4 text-green-500" />
<span></span>
</div>
<span className="font-bold text-green-600">¥{stats.thisMonthSpent.toFixed(2)}</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Users className="w-4 h-4 text-purple-500" />
<span></span>
</div>
<span className="font-bold">{stats.sharedCount} </span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Gift className="w-4 h-4 text-orange-500" />
<span></span>
</div>
<span className="font-bold text-orange-600">¥{stats.commissionEarned.toFixed(2)}</span>
</div>
</div>
</CardContent>
</Card>
{/* 快捷功能 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4">
<Button variant="outline" className="h-16 flex-col">
<CreditCard className="w-6 h-6 mb-2" />
<span className="text-sm"></span>
</Button>
<Button variant="outline" className="h-16 flex-col">
<MapPin className="w-6 h-6 mb-2" />
<span className="text-sm"></span>
</Button>
<Button variant="outline" className="h-16 flex-col">
<Bell className="w-6 h-6 mb-2" />
<span className="text-sm"></span>
</Button>
<Button variant="outline" className="h-16 flex-col">
<HelpCircle className="w-6 h-6 mb-2" />
<span className="text-sm"></span>
</Button>
</div>
</CardContent>
</Card>
</div>
</TabsContent>
{/* 订单 */}
<TabsContent value="orders" className="mt-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle></CardTitle>
<Button variant="outline" size="sm">
</Button>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{orders.map((order) => (
<div key={order.id} className="border rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-500">{order.id}</span>
<Badge variant="outline" className="text-xs">
{getOrderTypeBadge(order.type).label}
</Badge>
<Badge className={getStatusBadge(order.status).className}>
{getStatusBadge(order.status).label}
</Badge>
</div>
<span className="text-sm text-gray-500">{order.date}</span>
</div>
<div className="flex items-center gap-4 mb-3">
{order.items.map((item, index) => (
<div key={index} className="flex items-center gap-3">
<img
src={item.image}
alt={item.name}
className="w-12 h-12 object-cover rounded"
/>
<div>
<p className="font-medium text-sm">{item.name}</p>
<p className="text-xs text-gray-500">¥{item.price} × {item.quantity}</p>
</div>
</div>
))}
</div>
<div className="flex items-center justify-between">
<div className="text-right">
<p className="text-sm text-gray-600"></p>
<p className="text-lg font-bold text-red-500">¥{order.total.toFixed(2)}</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm">
</Button>
{order.status === 'delivered' && (
<Button variant="outline" size="sm">
</Button>
)}
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
{/* 收藏 */}
<TabsContent value="favorites" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{favorites.map((item) => (
<Card key={item.id} className="overflow-hidden hover:shadow-lg transition-shadow">
<div className="aspect-square">
<img
src={item.image}
alt={item.name}
className="w-full h-full object-cover"
/>
</div>
<CardContent className="p-4">
<h3 className="font-medium text-sm mb-1 line-clamp-2">{item.name}</h3>
<div className="flex items-center gap-1 mb-2">
<Star className="w-3 h-3 text-yellow-500 fill-current" />
<span className="text-xs text-gray-600">{item.rating}</span>
<span className="text-xs text-gray-400">({item.salesCount})</span>
</div>
<div className="flex items-center justify-between">
<div>
<span className="text-lg font-bold text-red-500">¥{item.price}</span>
{item.originalPrice > item.price && (
<span className="text-sm text-gray-400 line-through ml-1">
¥{item.originalPrice}
</span>
)}
</div>
<Button size="sm" variant="outline">
<Heart className="w-4 h-4" />
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
{/* 成就 */}
<TabsContent value="achievements" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{achievements.map((achievement) => (
<Card key={achievement.id} className={`${achievement.unlocked ? 'bg-gradient-to-br from-yellow-50 to-orange-50 border-yellow-200' : ''}`}>
<CardContent className="p-6">
<div className="flex items-center gap-4 mb-4">
<div className={`w-12 h-12 rounded-full flex items-center justify-center ${
achievement.unlocked
? 'bg-yellow-500'
: 'bg-gray-200'
}`}>
<achievement.icon className={`w-6 h-6 ${
achievement.unlocked ? 'text-white' : 'text-gray-400'
}`} />
</div>
<div className="flex-1">
<h3 className="font-semibold">{achievement.name}</h3>
<p className="text-sm text-gray-600">{achievement.description}</p>
</div>
{achievement.unlocked && (
<Trophy className="w-6 h-6 text-yellow-500" />
)}
</div>
{!achievement.unlocked && (
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span></span>
<span className="font-medium">
{achievement.progress}/{achievement.target}
</span>
</div>
<Progress
value={(achievement.progress / achievement.target) * 100}
className="h-2"
/>
</div>
)}
<div className="mt-3 p-2 bg-yellow-50 rounded text-sm">
<span className="text-yellow-800">{achievement.reward}</span>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
{/* 设置 */}
<TabsContent value="settings" className="mt-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 账户设置 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<User className="w-5 h-5 text-gray-500" />
<div>
<p className="font-medium"></p>
<p className="text-sm text-gray-500"></p>
</div>
</div>
<ChevronRight className="w-5 h-5 text-gray-400" />
</div>
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Shield className="w-5 h-5 text-gray-500" />
<div>
<p className="font-medium"></p>
<p className="text-sm text-gray-500"></p>
</div>
</div>
<ChevronRight className="w-5 h-5 text-gray-400" />
</div>
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Bell className="w-5 h-5 text-gray-500" />
<div>
<p className="font-medium"></p>
<p className="text-sm text-gray-500"></p>
</div>
</div>
<ChevronRight className="w-5 h-5 text-gray-400" />
</div>
</div>
</CardContent>
</Card>
{/* 其他设置 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<FileText className="w-5 h-5 text-gray-500" />
<div>
<p className="font-medium"></p>
<p className="text-sm text-gray-500"></p>
</div>
</div>
<ChevronRight className="w-5 h-5 text-gray-400" />
</div>
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<HelpCircle className="w-5 h-5 text-gray-500" />
<div>
<p className="font-medium"></p>
<p className="text-sm text-gray-500"></p>
</div>
</div>
<ChevronRight className="w-5 h-5 text-gray-400" />
</div>
<Button variant="outline" className="w-full mt-4 text-red-500 hover:text-red-600">
<LogOut className="w-4 h-4 mr-2" />
退
</Button>
</div>
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>
</div>
{/* 小程序风格底部导航栏 */}
<nav className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-100 safe-area-inset-bottom">
<div className="flex items-center justify-around py-2">
<a href="/" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<Home className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/group" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<ShoppingCart className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/distribution" className="flex flex-col items-center gap-1 py-1 text-gray-600 active:bg-gray-100 rounded-lg px-3">
<TrendingUp className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/profile" className="flex flex-col items-center gap-1 py-1 text-red-500 active:bg-red-50 rounded-lg px-3">
<Users className="w-5 h-5" />
<span className="text-xs"></span>
</a>
</div>
</nav>
</div>
)
}

View File

@ -0,0 +1,699 @@
'use client'
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { Slider } from '@/components/ui/slider'
import { Separator } from '@/components/ui/separator'
import {
Crown,
Star,
Gift,
Calendar,
Settings,
Sparkles,
Package,
Heart,
Truck,
Clock,
CheckCircle,
Lock,
Unlock,
RefreshCw,
Eye,
Share2,
ShoppingBag,
TrendingUp,
Users,
ShoppingCart,
Droplets,
Home
} from 'lucide-react'
export default function SubscriptionPage() {
const [activeTab, setActiveTab] = useState('plans')
const [showSubscribeDialog, setShowSubscribeDialog] = useState(false)
const [selectedPlan, setSelectedPlan] = useState('')
const [deliveryFrequency, setDeliveryFrequency] = useState('monthly')
const [deliveryDay, setDeliveryDay] = useState('5')
const [excludedScents, setExcludedScents] = useState<string[]>([])
const [scentIntensity, setScentIntensity] = useState([50])
// 模拟用户数据
const userSubscription = {
plan: 'tasting',
status: 'active',
nextDelivery: '2025-04-05',
unlockedScents: ['玫瑰', '薰衣草', '茉莉', '柑橘'],
points: 1280,
level: '品鉴会员',
joinDate: '2025-01-15',
totalDeliveries: 3,
skippedDeliveries: 0
}
const membershipPlans = [
{
id: 'explore',
name: '探索会员',
icon: Star,
color: 'blue',
price: 99,
originalPrice: 129,
discount: '95折',
benefits: [
'盲盒95折优惠',
'月返5%积分',
'基础客服支持',
'每月1次退换货',
'标准配送'
],
requirements: '无门槛',
popular: false,
features: ['4种香型', '基础包装', '标准配送']
},
{
id: 'tasting',
name: '品鉴会员',
icon: Crown,
color: 'purple',
price: 199,
originalPrice: 259,
discount: '85折',
benefits: [
'盲盒85折优惠',
'专属客服支持',
'分销订单奖10%积分',
'每月3次退换货',
'优先配送',
'生日专属礼品'
],
requirements: '累计消费满500元',
popular: true,
features: ['8种香型', '精美包装', '优先配送', '生日礼品']
},
{
id: 'perfumer',
name: '调香会员',
icon: Sparkles,
color: 'gold',
price: 399,
originalPrice: 499,
discount: '专属价',
benefits: [
'免费调香咨询',
'新品优先试用',
'积分兑线下体验',
'专属调香师服务',
'无限次退换货',
'VIP专属活动',
'定制化服务'
],
requirements: '累计消费满2000元',
popular: false,
features: ['12种香型+', '定制包装', '极速配送', '专属服务', '线下体验']
}
]
const scentCategories = [
{
category: '花香调',
scents: [
{ id: 'rose', name: '玫瑰', unlocked: true, description: '经典浪漫,优雅迷人' },
{ id: 'jasmine', name: '茉莉', unlocked: true, description: '清新淡雅,东方韵味' },
{ id: 'lily', name: '百合', unlocked: false, description: '纯洁高雅,花香浓郁' },
{ id: 'orchid', name: '兰花', unlocked: false, description: '神秘高贵,独特魅力' }
]
},
{
category: '果香调',
scents: [
{ id: 'citrus', name: '柑橘', unlocked: true, description: '清新活力,阳光明媚' },
{ id: 'apple', name: '苹果', unlocked: false, description: '甜美清新,自然纯粹' },
{ id: 'berry', name: '浆果', unlocked: false, description: '酸甜可口,诱人食欲' }
]
},
{
category: '木质调',
scents: [
{ id: 'sandalwood', name: '檀香', unlocked: false, description: '沉稳厚重,禅意十足' },
{ id: 'cedar', name: '雪松', unlocked: false, description: '清新自然,森林气息' }
]
},
{
category: '草本调',
scents: [
{ id: 'lavender', name: '薰衣草', unlocked: true, description: '舒缓放松,助眠安神' },
{ id: 'mint', name: '薄荷', unlocked: false, description: '清凉提神,清新口气' }
]
}
]
const deliveryHistory = [
{
id: '1',
date: '2025-03-05',
status: 'delivered',
scents: ['玫瑰', '薰衣草'],
rating: 5,
feedback: '很喜欢这个组合,香味很棒!',
image: '/api/placeholder/100/100'
},
{
id: '2',
date: '2025-02-05',
status: 'delivered',
scents: ['茉莉', '柑橘'],
rating: 4,
feedback: '茉莉香味很正宗,柑橘很清新',
image: '/api/placeholder/100/100'
},
{
id: '3',
date: '2025-01-05',
status: 'delivered',
scents: ['玫瑰'],
rating: 5,
feedback: '第一次订阅,体验很好',
image: '/api/placeholder/100/100'
}
]
const hiddenScents = [
{
id: 'secret1',
name: '午夜玫瑰',
description: '限量的深夜玫瑰香型,神秘而浪漫',
unlockCondition: '分享拼团链接至朋友圈满3次',
progress: 2,
target: 3,
image: '/api/placeholder/200/200'
},
{
id: 'secret2',
name: '晨露茉莉',
description: '清晨带露珠的茉莉,清新脱俗',
unlockCondition: '连续订阅3个月',
progress: 2,
target: 3,
image: '/api/placeholder/200/200'
}
]
const currentPlan = membershipPlans.find(plan => plan.id === userSubscription.plan)
const handleSubscribe = () => {
console.log('订阅计划:', selectedPlan)
console.log('配送频率:', deliveryFrequency)
console.log('配送日期:', deliveryDay)
console.log('排除香型:', excludedScents)
console.log('香型浓度:', scentIntensity[0])
setShowSubscribeDialog(false)
}
const toggleScentExclusion = (scentName: string) => {
setExcludedScents(prev =>
prev.includes(scentName)
? prev.filter(name => name !== scentName)
: [...prev, scentName]
)
}
return (
<div className="min-h-screen bg-gradient-to-br from-pink-50 to-purple-50">
{/* Header */}
<div className="bg-gradient-to-r from-pink-600 to-purple-600 text-white">
<div className="max-w-6xl mx-auto px-4 py-8">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-16 h-16 bg-white/20 backdrop-blur rounded-full flex items-center justify-center">
<Package className="w-8 h-8 text-white" />
</div>
<div>
<h1 className="text-3xl font-bold"></h1>
<p className="text-pink-100 mt-1"></p>
</div>
</div>
<div className="text-right">
<div className="flex items-center gap-4">
<div className="text-center">
<p className="text-sm text-pink-100"></p>
<p className="text-xl font-bold">{currentPlan?.name}</p>
</div>
<div className="text-center">
<p className="text-sm text-pink-100"></p>
<p className="text-xl font-bold">{userSubscription.nextDelivery}</p>
</div>
<div className="text-center">
<p className="text-sm text-pink-100"></p>
<p className="text-xl font-bold">{userSubscription.unlockedScents.length}</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="max-w-6xl mx-auto px-4 py-6">
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="plans"></TabsTrigger>
<TabsTrigger value="scents"></TabsTrigger>
<TabsTrigger value="history"></TabsTrigger>
<TabsTrigger value="settings"></TabsTrigger>
</TabsList>
{/* 订阅计划 */}
<TabsContent value="plans" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{membershipPlans.map((plan) => (
<Card key={plan.id} className={`relative overflow-hidden ${
plan.popular ? 'ring-2 ring-purple-500 shadow-lg' : ''
} ${plan.id === userSubscription.plan ? 'bg-gradient-to-br from-purple-50 to-pink-50' : ''}`}>
{plan.popular && (
<div className="absolute -top-3 left-1/2 transform -translate-x-1/2 z-10">
<Badge className="bg-purple-500 text-white px-3 py-1">
</Badge>
</div>
)}
{plan.id === userSubscription.plan && (
<div className="absolute top-4 right-4 z-10">
<Badge className="bg-green-500 text-white">
</Badge>
</div>
)}
<CardHeader className="text-center pb-4">
<div className="w-16 h-16 mx-auto mb-4 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
<plan.icon className="w-8 h-8 text-white" />
</div>
<CardTitle className="text-xl">{plan.name}</CardTitle>
<p className="text-sm text-gray-600">{plan.requirements}</p>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center">
<div className="flex items-baseline justify-center gap-2">
<span className="text-3xl font-bold text-purple-600">¥{plan.price}</span>
<span className="text-lg text-gray-400 line-through">¥{plan.originalPrice}</span>
</div>
<Badge variant="secondary" className="mt-1">{plan.discount}</Badge>
</div>
<div className="space-y-2">
<h4 className="font-semibold text-sm"></h4>
{plan.benefits.map((benefit, index) => (
<div key={index} className="flex items-center gap-2">
<CheckCircle className="w-4 h-4 text-green-500" />
<span className="text-sm">{benefit}</span>
</div>
))}
</div>
<div className="space-y-2">
<h4 className="font-semibold text-sm"></h4>
<div className="flex flex-wrap gap-1">
{plan.features.map((feature, index) => (
<Badge key={index} variant="outline" className="text-xs">
{feature}
</Badge>
))}
</div>
</div>
<Button
className={`w-full ${
plan.id === userSubscription.plan
? 'bg-gray-100 text-gray-600'
: plan.popular
? 'bg-purple-500 hover:bg-purple-600'
: ''
}`}
variant={plan.id === userSubscription.plan ? 'outline' : 'default'}
disabled={plan.id === userSubscription.plan}
>
{plan.id === userSubscription.plan ? '当前订阅' : '立即订阅'}
</Button>
</CardContent>
</Card>
))}
</div>
{/* 隐藏款香型 */}
<Card className="mt-8">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Lock className="w-5 h-5 text-orange-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{hiddenScents.map((scent) => (
<div key={scent.id} className="border rounded-lg p-4">
<div className="flex gap-4">
<img
src={scent.image}
alt={scent.name}
className="w-20 h-20 object-cover rounded-lg"
/>
<div className="flex-1">
<h3 className="font-semibold">{scent.name}</h3>
<p className="text-sm text-gray-600 mb-2">{scent.description}</p>
<p className="text-xs text-orange-600 mb-2">{scent.unlockCondition}</p>
<div className="space-y-1">
<div className="flex items-center justify-between text-xs">
<span></span>
<span>{scent.progress}/{scent.target}</span>
</div>
<Progress value={(scent.progress / scent.target) * 100} className="h-2" />
</div>
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
{/* 香型管理 */}
<TabsContent value="scents" className="mt-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{scentCategories.map((category) => (
<Card key={category.category}>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Droplets className="w-5 h-5 text-purple-500" />
{category.category}
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
{category.scents.map((scent) => (
<div key={scent.id} className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${
scent.unlocked
? 'bg-purple-100'
: 'bg-gray-100'
}`}>
{scent.unlocked ? (
<Unlock className="w-5 h-5 text-purple-600" />
) : (
<Lock className="w-5 h-5 text-gray-400" />
)}
</div>
<div>
<p className="font-medium">{scent.name}</p>
<p className="text-xs text-gray-500">{scent.description}</p>
</div>
</div>
<div className="flex items-center gap-2">
{scent.unlocked && (
<>
<Badge variant="outline" className="text-xs"></Badge>
<Checkbox
checked={excludedScents.includes(scent.name)}
onCheckedChange={() => toggleScentExclusion(scent.name)}
/>
</>
)}
{!scent.unlocked && (
<Badge variant="secondary" className="text-xs"></Badge>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
{/* 配送记录 */}
<TabsContent value="history" className="mt-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle></CardTitle>
<div className="flex items-center gap-2 text-sm text-gray-600">
<Package className="w-4 h-4" />
<span> {userSubscription.totalDeliveries} </span>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{deliveryHistory.map((delivery) => (
<div key={delivery.id} className="flex items-center justify-between p-4 border rounded-lg">
<div className="flex items-center gap-4">
<img
src={delivery.image}
alt="配送产品"
className="w-16 h-16 object-cover rounded-lg"
/>
<div>
<div className="flex items-center gap-2 mb-1">
<p className="font-medium">{delivery.date}</p>
<Badge className="bg-green-100 text-green-800 text-xs">
</Badge>
</div>
<p className="text-sm text-gray-600 mb-1">
{delivery.scents.join('、')}
</p>
<div className="flex items-center gap-1">
{[...Array(5)].map((_, i) => (
<Star
key={i}
className={`w-3 h-3 ${
i < delivery.rating
? 'text-yellow-500 fill-current'
: 'text-gray-300'
}`}
/>
))}
</div>
</div>
</div>
<div className="text-right">
<p className="text-sm text-gray-500 mb-2">{delivery.feedback}</p>
<div className="flex gap-2">
<Button variant="outline" size="sm">
<Eye className="w-4 h-4 mr-1" />
</Button>
<Button variant="outline" size="sm">
<RefreshCw className="w-4 h-4 mr-1" />
</Button>
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
{/* 订阅设置 */}
<TabsContent value="settings" className="mt-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 当前订阅信息 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<span className="font-medium">{currentPlan?.name}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<Badge className="bg-green-100 text-green-800"></Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<span className="font-medium">{userSubscription.nextDelivery}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<span className="font-medium"></span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<span className="font-medium">{userSubscription.totalDeliveries} </span>
</div>
<Separator />
<div className="flex gap-2">
<Button variant="outline" className="flex-1">
<Settings className="w-4 h-4 mr-2" />
</Button>
<Button variant="outline" className="flex-1">
<RefreshCw className="w-4 h-4 mr-2" />
</Button>
</div>
</CardContent>
</Card>
{/* 订阅配置 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label htmlFor="frequency"></Label>
<Select value={deliveryFrequency} onValueChange={setDeliveryFrequency}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly"></SelectItem>
<SelectItem value="semimonthly"></SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="delivery-day"></Label>
<Select value={deliveryDay} onValueChange={setDeliveryDay}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="15">15</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label></Label>
<div className="mt-2">
<Slider
value={scentIntensity}
onValueChange={setScentIntensity}
max={100}
min={10}
step={10}
className="w-full"
/>
<div className="flex justify-between text-xs text-gray-500 mt-1">
<span></span>
<span> ({scentIntensity[0]}%)</span>
<span></span>
</div>
</div>
</div>
<Button className="w-full"></Button>
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>
{/* 订阅对话框 */}
<Dialog open={showSubscribeDialog} onOpenChange={setShowSubscribeDialog}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="plan"></Label>
<Select value={selectedPlan} onValueChange={setSelectedPlan}>
<SelectTrigger>
<SelectValue placeholder="选择订阅计划" />
</SelectTrigger>
<SelectContent>
{membershipPlans.map((plan) => (
<SelectItem key={plan.id} value={plan.id}>
{plan.name} - ¥{plan.price}/
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="frequency"></Label>
<Select value={deliveryFrequency} onValueChange={setDeliveryFrequency}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly"></SelectItem>
<SelectItem value="semimonthly"></SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="delivery-day"></Label>
<Select value={deliveryDay} onValueChange={setDeliveryDay}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="15">15</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={() => setShowSubscribeDialog(false)} className="flex-1">
</Button>
<Button onClick={handleSubscribe} className="flex-1">
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{/* Bottom Navigation */}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t">
<div className="max-w-6xl mx-auto px-4">
<div className="grid grid-cols-4 py-2">
<a href="/" className="flex flex-col items-center gap-1 py-2 text-gray-500 hover:text-purple-500 transition-colors">
<Home className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/subscription" className="flex flex-col items-center gap-1 py-2 text-gray-500 hover:text-purple-500 transition-colors">
<ShoppingCart className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/distribution" className="flex flex-col items-center gap-1 py-2 text-gray-500 hover:text-purple-500 transition-colors">
<TrendingUp className="w-5 h-5" />
<span className="text-xs"></span>
</a>
<a href="/profile" className="flex flex-col items-center gap-1 py-2 text-gray-500 hover:text-purple-500 transition-colors">
<Users className="w-5 h-5" />
<span className="text-xs"></span>
</a>
</div>
</div>
</div>
</div>
)
}

View File

@ -0,0 +1,154 @@
import { motion } from 'framer-motion'
import { ReactNode } from 'react'
interface FadeInProps {
children: ReactNode
delay?: number
duration?: number
className?: string
}
export function FadeIn({ children, delay = 0, duration = 0.5, className }: FadeInProps) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration, delay }}
className={className}
>
{children}
</motion.div>
)
}
interface SlideInProps {
children: ReactNode
direction?: 'left' | 'right' | 'up' | 'down'
delay?: number
duration?: number
className?: string
}
export function SlideIn({
children,
direction = 'up',
delay = 0,
duration = 0.5,
className
}: SlideInProps) {
const getInitialPosition = () => {
switch (direction) {
case 'left': return { x: -50, y: 0 }
case 'right': return { x: 50, y: 0 }
case 'up': return { x: 0, y: 20 }
case 'down': return { x: 0, y: -20 }
default: return { x: 0, y: 20 }
}
}
return (
<motion.div
initial={{ opacity: 0, ...getInitialPosition() }}
animate={{ opacity: 1, x: 0, y: 0 }}
transition={{ duration, delay }}
className={className}
>
{children}
</motion.div>
)
}
interface ScaleInProps {
children: ReactNode
delay?: number
duration?: number
className?: string
}
export function ScaleIn({ children, delay = 0, duration = 0.3, className }: ScaleInProps) {
return (
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration, delay }}
className={className}
>
{children}
</motion.div>
)
}
interface StaggerContainerProps {
children: ReactNode
staggerDelay?: number
className?: string
}
export function StaggerContainer({ children, staggerDelay = 0.1, className }: StaggerContainerProps) {
return (
<motion.div
initial="hidden"
animate="visible"
variants={{
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
staggerChildren: staggerDelay
}
}
}}
className={className}
>
{children}
</motion.div>
)
}
export function StaggerItem({ children, className }: { children: ReactNode, className?: string }) {
return (
<motion.div
variants={{
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 }
}}
className={className}
>
{children}
</motion.div>
)
}
interface PulseProps {
children: ReactNode
className?: string
}
export function Pulse({ children, className }: PulseProps) {
return (
<motion.div
animate={{ scale: [1, 1.05, 1] }}
transition={{ duration: 2, repeat: Infinity }}
className={className}
>
{children}
</motion.div>
)
}
interface BounceProps {
children: ReactNode
className?: string
}
export function Bounce({ children, className }: BounceProps) {
return (
<motion.div
animate={{ y: [0, -10, 0] }}
transition={{ duration: 1, repeat: Infinity }}
className={className}
>
{children}
</motion.div>
)
}

View File

@ -0,0 +1,88 @@
'use client'
import { useState } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { Button } from '@/components/ui/button'
import {
Home,
Search,
PlusSquare,
ShoppingBag,
User
} from 'lucide-react'
export default function BottomNavigation() {
const router = useRouter()
const pathname = usePathname()
// 根据当前路径确定活跃标签
const getActiveTab = () => {
if (pathname === '/') return 'home'
if (pathname.startsWith('/discover')) return 'discover'
if (pathname.startsWith('/create')) return 'create'
if (pathname.startsWith('/orders')) return 'orders'
if (pathname.startsWith('/profile')) return 'profile'
return 'home'
}
const [activeTab, setActiveTab] = useState(getActiveTab())
const handleNavigation = (tab: string, path: string) => {
setActiveTab(tab)
router.push(path)
}
return (
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 z-50">
<div className="max-w-lg mx-auto">
<div className="flex items-center justify-around py-2">
<Button
variant="ghost"
size="sm"
className={`flex flex-col items-center gap-1 p-2 h-auto ${activeTab === 'home' ? 'text-purple-600' : 'text-gray-500'}`}
onClick={() => handleNavigation('home', '/')}
>
<Home className="w-5 h-5" />
<span className="text-xs"></span>
</Button>
<Button
variant="ghost"
size="sm"
className={`flex flex-col items-center gap-1 p-2 h-auto ${activeTab === 'discover' ? 'text-purple-600' : 'text-gray-500'}`}
onClick={() => handleNavigation('discover', '/discover')}
>
<Search className="w-5 h-5" />
<span className="text-xs"></span>
</Button>
<Button
variant="ghost"
size="sm"
className={`flex flex-col items-center gap-1 p-2 h-auto ${activeTab === 'create' ? 'text-purple-600' : 'text-gray-500'}`}
onClick={() => handleNavigation('create', '/create')}
>
<PlusSquare className="w-5 h-5" />
<span className="text-xs"></span>
</Button>
<Button
variant="ghost"
size="sm"
className={`flex flex-col items-center gap-1 p-2 h-auto ${activeTab === 'orders' ? 'text-purple-600' : 'text-gray-500'}`}
onClick={() => handleNavigation('orders', '/orders')}
>
<ShoppingBag className="w-5 h-5" />
<span className="text-xs"></span>
</Button>
<Button
variant="ghost"
size="sm"
className={`flex flex-col items-center gap-1 p-2 h-auto ${activeTab === 'profile' ? 'text-purple-600' : 'text-gray-500'}`}
onClick={() => handleNavigation('profile', '/profile')}
>
<User className="w-5 h-5" />
<span className="text-xs"></span>
</Button>
</div>
</div>
</div>
)
}

View File

@ -0,0 +1,272 @@
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Plus, X, Calendar, Gift } from 'lucide-react'
interface Prize {
id: string
name: string
total: number
probability: number
color: string
}
interface CreateActivityProps {
onActivityCreated?: (activity: any) => void
}
const prizeColors = [
'#ef4444', '#f97316', '#eab308', '#84cc16',
'#22c55e', '#06b6d4', '#3b82f6', '#8b5cf6'
]
export default function CreateActivity({ onActivityCreated }: CreateActivityProps) {
const [open, setOpen] = useState(false)
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [startDate, setStartDate] = useState('')
const [endDate, setEndDate] = useState('')
const [maxParticipants, setMaxParticipants] = useState('')
const [prizes, setPrizes] = useState<Prize[]>([
{ id: '1', name: '5元无门槛券', total: 100, probability: 30, color: '#ef4444' },
{ id: '2', name: '10元优惠券', total: 50, probability: 20, color: '#f97316' },
{ id: '3', name: '谢谢参与', total: 1000, probability: 50, color: '#6b7280' }
])
const addPrize = () => {
const newPrize: Prize = {
id: Date.now().toString(),
name: '',
total: 100,
probability: 10,
color: prizeColors[prizes.length % prizeColors.length]
}
setPrizes([...prizes, newPrize])
}
const updatePrize = (id: string, field: keyof Prize, value: string | number) => {
setPrizes(prizes.map(prize =>
prize.id === id ? { ...prize, [field]: value } : prize
))
}
const removePrize = (id: string) => {
if (prizes.length > 1) {
setPrizes(prizes.filter(prize => prize.id !== id))
}
}
const handleSubmit = () => {
const activity = {
id: Date.now().toString(),
title,
description,
startDate,
endDate,
maxParticipants: parseInt(maxParticipants) || 0,
prizes,
status: 'active',
createdAt: new Date().toISOString()
}
onActivityCreated?.(activity)
setOpen(false)
// 重置表单
setTitle('')
setDescription('')
setStartDate('')
setEndDate('')
setMaxParticipants('')
setPrizes([
{ id: '1', name: '5元无门槛券', total: 100, probability: 30, color: '#ef4444' },
{ id: '2', name: '10元优惠券', total: 50, probability: 20, color: '#f97316' },
{ id: '3', name: '谢谢参与', total: 1000, probability: 50, color: '#6b7280' }
])
}
const totalProbability = prizes.reduce((sum, prize) => sum + prize.probability, 0)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-red-500 hover:bg-red-600">
<Plus className="w-4 h-4 mr-1" />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Gift className="w-5 h-5 text-red-500" />
</DialogTitle>
</DialogHeader>
<div className="space-y-6">
{/* 基本信息 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label htmlFor="title"></Label>
<Input
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="请输入活动标题"
/>
</div>
<div>
<Label htmlFor="description"></Label>
<Textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="请输入活动描述"
rows={3}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="startDate"></Label>
<Input
id="startDate"
type="datetime-local"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
/>
</div>
<div>
<Label htmlFor="endDate"></Label>
<Input
id="endDate"
type="datetime-local"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
/>
</div>
</div>
<div>
<Label htmlFor="maxParticipants"></Label>
<Input
id="maxParticipants"
type="number"
value={maxParticipants}
onChange={(e) => setMaxParticipants(e.target.value)}
placeholder="不限制请留空"
/>
</div>
</CardContent>
</Card>
{/* 奖品设置 */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-base"></CardTitle>
<Button variant="outline" size="sm" onClick={addPrize}>
<Plus className="w-4 h-4 mr-1" />
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
{prizes.map((prize, index) => (
<div key={prize.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div
className="w-4 h-4 rounded-full"
style={{ backgroundColor: prize.color }}
/>
<span className="font-medium"> {index + 1}</span>
</div>
{prizes.length > 1 && (
<Button
variant="ghost"
size="sm"
onClick={() => removePrize(prize.id)}
className="text-red-500 hover:text-red-600"
>
<X className="w-4 h-4" />
</Button>
)}
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<Label></Label>
<Input
value={prize.name}
onChange={(e) => updatePrize(prize.id, 'name', e.target.value)}
placeholder="请输入奖品名称"
/>
</div>
<div>
<Label></Label>
<Input
type="number"
value={prize.total}
onChange={(e) => updatePrize(prize.id, 'total', parseInt(e.target.value) || 0)}
placeholder="数量"
/>
</div>
<div>
<Label> (%)</Label>
<Input
type="number"
value={prize.probability}
onChange={(e) => updatePrize(prize.id, 'probability', parseInt(e.target.value) || 0)}
placeholder="概率"
/>
</div>
</div>
</div>
))}
<div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<span className="text-sm font-medium"></span>
<Badge variant={totalProbability === 100 ? "default" : "destructive"}>
{totalProbability}%
</Badge>
</div>
{totalProbability !== 100 && (
<p className="text-sm text-red-500">
100%{totalProbability}%
</p>
)}
</CardContent>
</Card>
{/* 操作按钮 */}
<div className="flex gap-3 pt-4">
<Button variant="outline" onClick={() => setOpen(false)} className="flex-1">
</Button>
<Button
onClick={handleSubmit}
className="flex-1 bg-red-500 hover:bg-red-600"
disabled={!title || !startDate || !endDate || totalProbability !== 100}
>
</Button>
</div>
</div>
</DialogContent>
</Dialog>
)
}

View File

@ -0,0 +1,429 @@
'use client'
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Separator } from '@/components/ui/separator'
import {
Users,
TrendingUp,
DollarSign,
Gift,
Crown,
Target,
Award,
Copy,
MessageCircle,
Download,
Star,
Zap
} from 'lucide-react'
export default function DistributionDashboard() {
const [activeTab, setActiveTab] = useState('overview')
// 模拟数据
const stats = {
totalCommission: 2580.50,
todayCommission: 156.00,
teamSize: 23,
activeMembers: 18,
level: '品鉴分销员',
nextLevelProgress: 65
}
const teamMembers = [
{
id: '1',
name: '小美',
avatar: '小',
level: '探索分销员',
joinTime: '2025-03-15',
totalOrders: 15,
commission: 234.50,
status: 'active'
},
{
id: '2',
name: '香香公主',
avatar: '香',
level: '品鉴分销员',
joinTime: '2025-03-10',
totalOrders: 28,
commission: 456.80,
status: 'active'
},
{
id: '3',
name: '花仙子',
avatar: '花',
level: '调香分销员',
joinTime: '2025-03-01',
totalOrders: 42,
commission: 789.20,
status: 'active'
}
]
const commissions = [
{
id: '1',
orderNo: 'ORD20250402001',
customerName: '张小姐',
productName: '经典玫瑰香水30ml',
type: 'direct',
amount: 19.90,
rate: 0.10,
status: 'settled',
time: '2025-04-02 14:30'
},
{
id: '2',
orderNo: 'ORD20250402002',
customerName: '李女士',
productName: '薰衣草精油礼盒',
type: 'indirect',
amount: 14.95,
rate: 0.05,
status: 'pending',
time: '2025-04-02 13:15'
},
{
id: '3',
orderNo: 'ORD20250402001',
customerName: '王小姐',
productName: '小样体验包',
type: 'direct',
amount: 0.10,
rate: 0.10,
status: 'settled',
time: '2025-04-02 10:45'
}
]
const materials = [
{
id: '1',
title: '宝妈话术模板',
content: '自用省50分享赚100香氛好物自用省钱分享赚钱',
category: '话术',
usage: 1250,
rating: 4.8
},
{
id: '2',
title: '产品种草文案',
content: '这款玫瑰香水太绝了!留香一整天,闺蜜都问我要链接',
category: '文案',
usage: 890,
rating: 4.6
},
{
id: '3',
title: '拼团分享海报',
content: '精美海报模板,一键生成分享图',
category: '海报',
usage: 2100,
rating: 4.9
}
]
const tasks = [
{
id: '1',
title: '邀请3位好友',
description: '成功邀请3位好友注册并完成首单',
reward: '解锁高佣金商品推广权',
progress: 2,
target: 3,
status: 'in_progress'
},
{
id: '2',
title: '月销10单',
description: '本月完成10笔有效订单',
reward: '获得限量香氛礼品',
progress: 7,
target: 10,
status: 'in_progress'
},
{
id: '3',
title: '团队建设',
description: '团队人数达到20人',
reward: '晋升为调香分销员',
progress: 23,
target: 20,
status: 'completed'
}
]
const copyInviteCode = async () => {
const inviteCode = 'FRAGRANCE2025'
const inviteUrl = `${window.location.origin}/register?code=${inviteCode}`
try {
await navigator.clipboard.writeText(inviteUrl)
alert('邀请链接已复制到剪贴板')
} catch (error) {
console.error('复制失败')
}
}
return (
<div className="min-h-screen bg-gray-50 p-4">
<div className="max-w-6xl mx-auto">
{/* Header */}
<div className="bg-white rounded-lg shadow-sm p-6 mb-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
<Crown className="w-6 h-6 text-white" />
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900"></h1>
<p className="text-gray-600">{stats.level}</p>
</div>
</div>
<div className="flex items-center gap-4">
<div className="text-right">
<p className="text-sm text-gray-600"></p>
<p className="text-2xl font-bold text-green-600">¥{stats.totalCommission.toFixed(2)}</p>
</div>
<Button onClick={copyInviteCode}>
<Copy className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="overview"></TabsTrigger>
<TabsTrigger value="team"></TabsTrigger>
<TabsTrigger value="materials"></TabsTrigger>
<TabsTrigger value="tasks"></TabsTrigger>
</TabsList>
{/* 数据概览 */}
<TabsContent value="overview" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600"></p>
<p className="text-2xl font-bold text-green-600">¥{stats.todayCommission.toFixed(2)}</p>
</div>
<DollarSign className="w-8 h-8 text-green-500" />
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600"></p>
<p className="text-2xl font-bold text-blue-600">{stats.teamSize}</p>
</div>
<Users className="w-8 h-8 text-blue-500" />
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600"></p>
<p className="text-2xl font-bold text-purple-600">{stats.activeMembers}</p>
</div>
<TrendingUp className="w-8 h-8 text-purple-500" />
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600"></p>
<p className="text-2xl font-bold text-orange-600">{stats.nextLevelProgress}%</p>
</div>
<Award className="w-8 h-8 text-orange-500" />
</div>
</CardContent>
</Card>
</div>
{/* 佣金明细 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{commissions.map((commission) => (
<div key={commission.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium">{commission.customerName}</span>
<Badge variant={commission.type === 'direct' ? 'default' : 'secondary'}>
{commission.type === 'direct' ? '直推' : '间推'}
</Badge>
<Badge variant={commission.status === 'settled' ? 'default' : 'outline'}>
{commission.status === 'settled' ? '已结算' : '待结算'}
</Badge>
</div>
<p className="text-sm text-gray-600">{commission.productName}</p>
<p className="text-xs text-gray-500">{commission.orderNo} · {commission.time}</p>
</div>
<div className="text-right">
<p className="text-lg font-bold text-green-600">¥{commission.amount.toFixed(2)}</p>
<p className="text-xs text-gray-500">{(commission.rate * 100).toFixed(0)}%</p>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
{/* 团队管理 */}
<TabsContent value="team" className="mt-6">
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{teamMembers.map((member) => (
<div key={member.id} className="flex items-center justify-between p-4 border rounded-lg">
<div className="flex items-center gap-3">
<Avatar className="w-10 h-10">
<AvatarFallback>{member.avatar}</AvatarFallback>
</Avatar>
<div>
<p className="font-medium">{member.name}</p>
<p className="text-sm text-gray-600">{member.level}</p>
</div>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="font-bold">{member.totalOrders}</p>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="font-bold text-green-600">¥{member.commission.toFixed(2)}</p>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="text-sm">{member.joinTime}</p>
</div>
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${member.status === 'active' ? 'bg-green-500' : 'bg-gray-400'}`} />
<span className="text-sm">{member.status === 'active' ? '活跃' : '离线'}</span>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
{/* 素材库 */}
<TabsContent value="materials" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{materials.map((material) => (
<Card key={material.id}>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-base">{material.title}</CardTitle>
<Badge variant="outline">{material.category}</Badge>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-gray-600 mb-4">{material.content}</p>
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-1">
<Star className="w-4 h-4 text-yellow-500" />
<span className="text-sm">{material.rating}</span>
</div>
<span className="text-sm text-gray-500">使 {material.usage} </span>
</div>
<div className="flex gap-2">
<Button size="sm" variant="outline" className="flex-1">
<Copy className="w-4 h-4 mr-1" />
</Button>
<Button size="sm" variant="outline" className="flex-1">
<Download className="w-4 h-4 mr-1" />
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
{/* 任务体系 */}
<TabsContent value="tasks" className="mt-6">
<div className="space-y-4">
{tasks.map((task) => (
<Card key={task.id}>
<CardContent className="p-6">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-3">
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${
task.status === 'completed' ? 'bg-green-100' : 'bg-blue-100'
}`}>
{task.status === 'completed' ? (
<Award className="w-5 h-5 text-green-600" />
) : (
<Target className="w-5 h-5 text-blue-600" />
)}
</div>
<div>
<h3 className="font-semibold">{task.title}</h3>
<p className="text-sm text-gray-600">{task.description}</p>
</div>
</div>
<Badge variant={task.status === 'completed' ? 'default' : 'secondary'}>
{task.status === 'completed' ? '已完成' : '进行中'}
</Badge>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span></span>
<span>{task.progress}/{task.target}</span>
</div>
<Progress
value={(task.progress / task.target) * 100}
className="h-2"
/>
</div>
<div className="mt-4 p-3 bg-yellow-50 rounded-lg">
<div className="flex items-center gap-2">
<Gift className="w-4 h-4 text-yellow-600" />
<span className="text-sm font-medium text-yellow-800">{task.reward}</span>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
</Tabs>
</div>
</div>
)
}

View File

@ -0,0 +1,363 @@
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Separator } from '@/components/ui/separator'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import {
Users,
Clock,
Share2,
QrCode,
Truck,
Package,
Shield,
Award,
Link2,
Eye,
CheckCircle,
Crown
} from 'lucide-react'
interface GroupBuyDetailProps {
groupBuyId: string
product: any
groupBuy: any
members: any[]
}
export default function GroupBuyDetail({ groupBuyId, product, groupBuy, members }: GroupBuyDetailProps) {
const [timeRemaining, setTimeRemaining] = useState('')
const [showTraceDialog, setShowTraceDialog] = useState(false)
useEffect(() => {
const calculateTimeRemaining = () => {
const now = new Date()
const endTime = new Date(groupBuy.endTime)
const diff = endTime.getTime() - now.getTime()
if (diff <= 0) {
setTimeRemaining('已结束')
return
}
const hours = Math.floor(diff / (1000 * 60 * 60))
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((diff % (1000 * 60)) / 1000)
setTimeRemaining(`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`)
}
calculateTimeRemaining()
const timer = setInterval(calculateTimeRemaining, 1000)
return () => clearInterval(timer)
}, [groupBuy.endTime])
const handleShare = async () => {
const shareUrl = `${window.location.origin}/group-buy/${groupBuyId}`
const shareText = `快来参与「${product.name}」拼团,${groupBuy.targetPeople}人团享${groupBuy.targetPeople === 3 ? '7折' : '5折'}`
if (navigator.share) {
try {
await navigator.share({
title: product.name,
text: shareText,
url: shareUrl
})
} catch (error) {
console.log('分享取消或失败')
}
} else {
// 降级处理:复制链接
await navigator.clipboard.writeText(`${shareText} ${shareUrl}`)
alert('分享链接已复制到剪贴板')
}
}
const TraceCodeDialog = () => (
<Dialog open={showTraceDialog} onOpenChange={setShowTraceDialog}>
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<QrCode className="w-5 h-5 text-blue-500" />
</DialogTitle>
</DialogHeader>
<div className="space-y-6">
{/* 溯源码 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="font-mono text-lg font-bold">{groupBuy.traceCode || 'GB20250402001'}</div>
<Button variant="outline" size="sm">
<QrCode className="w-4 h-4 mr-2" />
</Button>
</div>
</CardContent>
</Card>
{/* 参团成员关系树 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
{members.map((member, index) => (
<div key={member.id} className="flex items-center gap-3">
<div className="flex items-center gap-2">
{index === 0 && <Crown className="w-4 h-4 text-yellow-500" />}
<Avatar className="w-8 h-8">
<AvatarFallback className="text-xs">{member.name?.[0] || '用'}</AvatarFallback>
</Avatar>
</div>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="font-medium">{member.name}</span>
{member.isLeader && <Badge className="bg-yellow-100 text-yellow-800"></Badge>}
</div>
<div className="text-xs text-gray-500">
{member.inviterName ? `${member.inviterName} 邀请` : '发起拼团'}
</div>
</div>
<div className="text-xs text-gray-400">
{new Date(member.joinTime).toLocaleString()}
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* 采购直播回放 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<div className="aspect-video bg-gray-100 rounded-lg flex items-center justify-center">
<div className="text-center">
<Eye className="w-12 h-12 text-gray-400 mx-auto mb-2" />
<p className="text-gray-500"></p>
<p className="text-sm text-gray-400 mt-1">2025-03-25 </p>
</div>
</div>
</CardContent>
</Card>
{/* 物流轨迹 */}
<Card>
<CardHeader>
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex items-start gap-3">
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5" />
<div className="flex-1">
<p className="font-medium"></p>
<p className="text-sm text-gray-500">2025-04-01 14:30 </p>
</div>
</div>
<div className="flex items-start gap-3">
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5" />
<div className="flex-1">
<p className="font-medium"></p>
<p className="text-sm text-gray-500">2025-04-01 08:00 </p>
</div>
</div>
<div className="flex items-start gap-3">
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5" />
<div className="flex-1">
<p className="font-medium"></p>
<p className="text-sm text-gray-500">2025-03-30 16:20 </p>
</div>
</div>
<div className="flex items-start gap-3">
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5" />
<div className="flex-1">
<p className="font-medium"></p>
<p className="text-sm text-gray-500">2025-03-28 10:15 </p>
</div>
</div>
<div className="flex items-start gap-3">
<Package className="w-4 h-4 text-blue-500 mt-0.5" />
<div className="flex-1">
<p className="font-medium"></p>
<p className="text-sm text-gray-500">2025-03-26 </p>
</div>
</div>
</div>
</CardContent>
</Card>
{/* 区块链存证 */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Shield className="w-4 h-4 text-blue-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="p-3 bg-blue-50 rounded-lg">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium"></span>
<Badge variant="outline" className="text-xs"></Badge>
</div>
<p className="text-xs text-gray-600 mb-2">区块高度: 1,234,567</p>
<p className="text-xs text-gray-500 mb-3">交易哈希: 0x7f9a...3b2c</p>
<Button variant="outline" size="sm" className="w-full">
<Link2 className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
</CardContent>
</Card>
</div>
</DialogContent>
</Dialog>
)
return (
<div className="space-y-6">
{/* 团购进度 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="w-5 h-5 text-purple-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Avatar className="w-8 h-8">
<AvatarFallback className="text-xs">{members[0]?.name?.[0] || '团'}</AvatarFallback>
</Avatar>
<div>
<p className="font-medium">{members[0]?.name || '团长'}</p>
<p className="text-sm text-gray-500"></p>
</div>
</div>
<div className="text-right">
<p className="text-2xl font-bold text-purple-600">
{groupBuy.currentPeople}/{groupBuy.targetPeople}
</p>
<p className="text-sm text-gray-500"></p>
</div>
</div>
<Progress
value={(groupBuy.currentPeople / groupBuy.targetPeople) * 100}
className="h-3"
/>
<div className="flex items-center justify-between text-sm">
<span className="text-gray-600"> {groupBuy.targetPeople - groupBuy.currentPeople} </span>
<div className="flex items-center gap-1">
<Clock className="w-4 h-4" />
<span className={timeRemaining === '已结束' ? 'text-red-500' : 'text-orange-500'}>
{timeRemaining}
</span>
</div>
</div>
</div>
</CardContent>
</Card>
{/* 价格信息 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<span className="text-lg text-gray-400 line-through">¥{product.originalPrice}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<span className="text-2xl font-bold text-red-500">¥{groupBuy.groupPrice}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-600"></span>
<Badge className="bg-yellow-100 text-yellow-800">
{groupBuy.targetPeople === 3 ? '200积分' : '300积分'}
</Badge>
</div>
</div>
</CardContent>
</Card>
{/* 参团成员 */}
<Card>
<CardHeader>
<CardTitle> ({members.length})</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
{members.map((member, index) => (
<div key={member.id} className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="relative">
<Avatar className="w-8 h-8">
<AvatarFallback className="text-xs">{member.name?.[0] || '用'}</AvatarFallback>
</Avatar>
{index === 0 && (
<Crown className="w-3 h-3 text-yellow-500 absolute -top-1 -right-1" />
)}
</div>
<div>
<p className="font-medium">{member.name}</p>
<p className="text-xs text-gray-500">
{member.inviterName ? `${member.inviterName} 邀请` : '发起拼团'}
</p>
</div>
</div>
<div className="text-xs text-gray-400">
{new Date(member.joinTime).toLocaleString()}
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* 操作按钮 */}
<div className="flex gap-3">
<Button className="flex-1 bg-purple-500 hover:bg-purple-600">
<Users className="w-4 h-4 mr-2" />
</Button>
<Button variant="outline" onClick={handleShare}>
<Share2 className="w-4 h-4 mr-2" />
</Button>
<Dialog open={showTraceDialog} onOpenChange={setShowTraceDialog}>
<DialogTrigger asChild>
<Button variant="outline">
<QrCode className="w-4 h-4 mr-2" />
</Button>
</DialogTrigger>
</Dialog>
</div>
<TraceCodeDialog />
</div>
)
}

View File

@ -0,0 +1,347 @@
'use client'
import { useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import {
Heart,
Send,
Clock,
Users,
Star,
Gift,
Zap,
TrendingUp
} from 'lucide-react'
interface GroupCardProps {
activity: {
id: string
title: string
image: string
originalPrice: number
groupPrice: number
groupSize: number
currentMembers: number
timeLeft: string
host: string
hostAvatar: string
likes: number
comments: number
isHot?: boolean
urgency?: 'high' | 'medium' | 'low'
}
onLike: (id: string) => void
onShare: (title: string) => void
onJoin: (id: string) => void
onViewDetails: (id: string) => void
isLiked: boolean
isJoined: boolean
variant?: 'default' | 'compact' | 'featured'
}
export function GroupCard({
activity,
onLike,
onShare,
onJoin,
onViewDetails,
isLiked,
isJoined,
variant = 'default'
}: GroupCardProps) {
const [isHovered, setIsHovered] = useState(false)
const [imageLoaded, setImageLoaded] = useState(false)
const progress = (activity.currentMembers / activity.groupSize) * 100
const remainingMembers = activity.groupSize - activity.currentMembers
const savingsAmount = activity.originalPrice - activity.groupPrice
const discountPercentage = Math.round((savingsAmount / activity.originalPrice) * 100)
// 根据剩余时间判断紧急程度
const getUrgencyLevel = () => {
const timeText = activity.timeLeft
if (timeText.includes('分') && !timeText.includes('小时')) return 'high'
if (timeText.includes('1小时') || timeText.includes('2小时')) return 'medium'
return 'low'
}
const urgencyLevel = activity.urgency || getUrgencyLevel()
if (variant === 'compact') {
return (
<Card
className="group border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl overflow-hidden cursor-pointer transform hover:scale-[1.02]"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onClick={() => onViewDetails(activity.id)}
>
<div className="flex">
{/* 图片区域 */}
<div className="relative w-24 h-24 flex-shrink-0">
<img
src={activity.image}
alt={activity.title}
className={`w-full h-full object-cover transition-all duration-500 ${
imageLoaded ? 'opacity-100' : 'opacity-0'
}`}
onLoad={() => setImageLoaded(true)}
/>
<div className="absolute top-1 left-1">
<Badge className="bg-red-500 text-white text-xs px-1.5 py-0.5 rounded-full">
</Badge>
</div>
</div>
{/* 内容区域 */}
<div className="flex-1 p-3">
<h3 className="font-semibold text-sm mb-1 line-clamp-1">{activity.title}</h3>
<div className="flex items-center gap-2 mb-2">
<span className="text-lg font-bold text-red-500">¥{activity.groupPrice}</span>
<span className="text-xs text-gray-400 line-through">¥{activity.originalPrice}</span>
</div>
<div className="flex items-center justify-between text-xs text-gray-500">
<span className="flex items-center gap-1">
<Users className="w-3 h-3" />
{activity.currentMembers}/{activity.groupSize}
</span>
<span className="flex items-center gap-1 text-red-500">
<Clock className="w-3 h-3" />
{activity.timeLeft}
</span>
</div>
</div>
</div>
</Card>
)
}
return (
<Card
className="group border-0 shadow-lg hover:shadow-2xl transition-all duration-500 rounded-3xl overflow-hidden cursor-pointer transform hover:scale-[1.01]"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* 图片区域 */}
<div className="relative">
<div className="aspect-[4/3] overflow-hidden bg-gradient-to-br from-gray-100 to-gray-200">
<img
src={activity.image}
alt={activity.title}
className={`w-full h-full object-cover transition-all duration-700 ${
imageLoaded ? 'opacity-100 scale-100' : 'opacity-0 scale-110'
} ${isHovered ? 'scale-110' : 'scale-100'}`}
onLoad={() => setImageLoaded(true)}
/>
{/* 渐变遮罩 */}
<div className="absolute inset-0 bg-gradient-to-t from-black/30 via-transparent to-transparent" />
</div>
{/* 状态标签 */}
<div className="absolute top-4 left-4 flex flex-wrap gap-2">
<Badge className={`backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full shadow-lg flex items-center gap-1 ${
urgencyLevel === 'high' ? 'bg-red-500/90 animate-pulse' :
urgencyLevel === 'medium' ? 'bg-orange-500/90' : 'bg-green-500/90'
}`}>
<Zap className="w-3 h-3" />
</Badge>
{activity.isHot && (
<Badge className="bg-red-600/90 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full shadow-lg flex items-center gap-1">
<TrendingUp className="w-3 h-3" />
</Badge>
)}
{discountPercentage > 0 && (
<Badge className="bg-purple-500/90 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full shadow-lg">
{discountPercentage}%
</Badge>
)}
</div>
{/* 快捷操作 */}
<div className={`absolute top-4 right-4 flex gap-2 transition-all duration-300 ${
isHovered ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-2'
}`}>
<Button
variant="ghost"
size="sm"
className="bg-white/20 backdrop-blur-md text-white p-2.5 rounded-full shadow-lg hover:bg-white/30"
onClick={(e) => {
e.stopPropagation()
onLike(activity.id)
}}
>
<Heart className={`w-5 h-5 ${isLiked ? 'fill-current text-red-400' : ''}`} />
</Button>
<Button
variant="ghost"
size="sm"
className="bg-white/20 backdrop-blur-md text-white p-2.5 rounded-full shadow-lg hover:bg-white/30"
onClick={(e) => {
e.stopPropagation()
onShare(activity.title)
}}
>
<Send className="w-5 h-5" />
</Button>
</div>
{/* 紧急提醒 */}
{urgencyLevel === 'high' && (
<div className="absolute bottom-4 left-4">
<Badge className="bg-red-500/90 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full shadow-lg animate-bounce">
<Clock className="w-3 h-3 mr-1" />
</Badge>
</div>
)}
</div>
<CardContent className="p-6">
<div className="space-y-4">
{/* 标题 */}
<h3 className="font-bold text-xl mb-2 line-clamp-2 leading-tight">{activity.title}</h3>
{/* 团长信息 */}
<div className="flex items-center gap-3 p-3 bg-gray-50 rounded-2xl">
<Avatar className="w-10 h-10 ring-2 ring-purple-200">
<AvatarFallback className="text-sm bg-gradient-to-r from-purple-500 to-pink-500 text-white font-semibold">
{activity.hostAvatar}
</AvatarFallback>
</Avatar>
<div className="flex-1">
<p className="text-sm font-semibold text-gray-800">{activity.host}</p>
<p className="text-xs text-gray-500 flex items-center gap-1">
<Users className="w-3 h-3" />
{remainingMembers}
</p>
</div>
<div className="text-right">
<div className="flex items-center gap-1 text-yellow-500">
<Star className="w-4 h-4 fill-current" />
<span className="text-sm font-semibold">4.9</span>
</div>
<p className="text-xs text-gray-500"></p>
</div>
</div>
{/* 价格信息 */}
<div className="flex items-center justify-between p-4 bg-gradient-to-r from-red-50 to-orange-50 rounded-2xl">
<div>
<div className="flex items-baseline gap-3 mb-1">
<span className="text-3xl font-bold text-red-500">¥{activity.groupPrice}</span>
<span className="text-lg text-gray-400 line-through">¥{activity.originalPrice}</span>
</div>
<p className="text-sm text-gray-600"></p>
</div>
<div className="text-right">
<Badge className="bg-red-500 text-white text-sm px-3 py-1 rounded-full mb-1">
<Gift className="w-3 h-3 mr-1" />
¥{savingsAmount}
</Badge>
<p className="text-xs text-gray-500">{discountPercentage}%</p>
</div>
</div>
{/* 进度条 */}
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-sm font-medium text-gray-700"></span>
<span className="text-sm font-bold text-purple-600">{activity.currentMembers}/{activity.groupSize}</span>
</div>
<div className="relative">
<Progress
value={progress}
className="h-3 bg-gray-200 rounded-full overflow-hidden"
/>
<div className="absolute inset-0 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full transition-all duration-500"
style={{ width: `${progress}%` }} />
</div>
<div className="flex justify-between text-xs text-gray-500">
<span> {activity.currentMembers} </span>
<span> {remainingMembers} </span>
</div>
</div>
{/* 倒计时 */}
<div className={`flex items-center justify-center gap-2 p-3 rounded-2xl ${
urgencyLevel === 'high' ? 'bg-red-50 text-red-600' :
urgencyLevel === 'medium' ? 'bg-orange-50 text-orange-600' : 'bg-green-50 text-green-600'
}`}>
<Clock className="w-5 h-5" />
<span className="font-semibold">{activity.timeLeft}</span>
</div>
{/* 操作按钮 */}
<div className="flex items-center justify-between pt-4 border-t border-gray-100">
<div className="flex items-center gap-6">
<Button
variant="ghost"
size="sm"
className="flex items-center gap-2 text-gray-600 hover:text-red-500 transition-colors"
onClick={(e) => {
e.stopPropagation()
onLike(activity.id)
}}
>
<Heart className={`w-5 h-5 ${isLiked ? 'fill-red-500 text-red-500' : ''}`} />
<span className="text-sm font-medium">{activity.likes}</span>
</Button>
<Button
variant="ghost"
size="sm"
className="flex items-center gap-2 text-gray-600 hover:text-blue-500 transition-colors"
onClick={(e) => {
e.stopPropagation()
onShare(activity.title)
}}
>
<Send className="w-5 h-5" />
<span className="text-sm font-medium">{activity.comments}</span>
</Button>
</div>
<div className="flex gap-3">
{isJoined ? (
<Button
variant="outline"
className="px-6 py-2.5 border-purple-200 text-purple-600 hover:bg-purple-50 rounded-full font-semibold"
onClick={(e) => {
e.stopPropagation()
onViewDetails(activity.id)
}}
>
</Button>
) : (
<Button
className={`px-8 py-2.5 text-white font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105 ${
urgencyLevel === 'high'
? 'bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 animate-pulse'
: 'bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600'
}`}
onClick={(e) => {
e.stopPropagation()
onJoin(activity.id)
}}
>
<Users className="w-4 h-4 mr-2" />
{urgencyLevel === 'high' ? '立即参团' : '参与拼团'}
</Button>
)}
</div>
</div>
</div>
</CardContent>
</Card>
)
}

View File

@ -0,0 +1,104 @@
import { Skeleton } from "@/components/ui/skeleton"
export function ProductCardSkeleton({ variant = 'default' }: { variant?: 'default' | 'compact' | 'featured' }) {
if (variant === 'compact') {
return (
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
<Skeleton className="w-full h-32" />
<div className="p-3 space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-3 w-1/2" />
<div className="flex items-center justify-between">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-8 w-16 rounded-full" />
</div>
</div>
</div>
)
}
return (
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
<Skeleton className="w-full h-64" />
<div className="p-4 space-y-3">
<Skeleton className="h-5 w-3/4" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
<div className="flex items-center gap-3">
<Skeleton className="h-6 w-20" />
<Skeleton className="h-4 w-16" />
</div>
<div className="flex items-center justify-between pt-3">
<div className="flex gap-4">
<Skeleton className="h-8 w-12" />
<Skeleton className="h-8 w-12" />
</div>
<Skeleton className="h-10 w-24 rounded-full" />
</div>
</div>
</div>
)
}
export function GroupCardSkeleton({ variant = 'default' }: { variant?: 'default' | 'compact' }) {
if (variant === 'compact') {
return (
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
<Skeleton className="w-full h-40" />
<div className="p-3 space-y-2">
<Skeleton className="h-4 w-3/4" />
<div className="flex items-center gap-2">
<Skeleton className="h-6 w-6 rounded-full" />
<Skeleton className="h-3 w-20" />
</div>
<Skeleton className="h-5 w-16" />
<Skeleton className="h-2 w-full" />
<Skeleton className="h-8 w-full rounded-full" />
</div>
</div>
)
}
return (
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
<Skeleton className="w-full h-48" />
<div className="p-4 space-y-3">
<Skeleton className="h-5 w-3/4" />
<div className="flex items-center gap-3">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-3 w-24" />
</div>
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-6 w-20" />
<Skeleton className="h-4 w-16" />
</div>
<div className="space-y-2">
<div className="flex justify-between">
<Skeleton className="h-3 w-16" />
<Skeleton className="h-3 w-12" />
</div>
<Skeleton className="h-2 w-full" />
</div>
<Skeleton className="h-4 w-24" />
<div className="flex items-center justify-between pt-3">
<div className="flex gap-4">
<Skeleton className="h-8 w-12" />
<Skeleton className="h-8 w-12" />
</div>
<Skeleton className="h-10 w-24 rounded-full" />
</div>
</div>
</div>
)
}
export function LoadingSpinner() {
return (
<div className="flex items-center justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
</div>
)
}

View File

@ -0,0 +1,245 @@
'use client'
import { useState, useRef, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Gift, RotateCw, Sparkles } from 'lucide-react'
interface Prize {
id: string
name: string
color: string
probability: number
remaining: number
total: number
}
interface LotteryWheelProps {
prizes: Prize[]
onSpinComplete?: (prize: Prize) => void
disabled?: boolean
}
export default function LotteryWheel({ prizes, onSpinComplete, disabled = false }: LotteryWheelProps) {
const [isSpinning, setIsSpinning] = useState(false)
const [rotation, setRotation] = useState(0)
const [selectedPrize, setSelectedPrize] = useState<Prize | null>(null)
const [showResult, setShowResult] = useState(false)
const wheelRef = useRef<HTMLDivElement>(null)
const segmentAngle = 360 / prizes.length
const spinWheel = async () => {
if (isSpinning || disabled) return
setIsSpinning(true)
setShowResult(false)
try {
// 调用API进行抽奖
const response = await fetch('/api/lottery/spin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
activityId: 'demo-activity',
userId: 'demo-user',
prizes: prizes.map(prize => ({
id: prize.id,
name: prize.name,
probability: prize.probability,
remaining: prize.remaining,
total: prize.total
}))
})
})
const result = await response.json()
if (!result.success) {
throw new Error(result.error || '抽奖失败')
}
// 找到对应的奖品
const selectedPrize = prizes.find(prize => prize.id === result.prize.id)
if (!selectedPrize) {
throw new Error('奖品信息不匹配')
}
// 计算旋转角度
const prizeIndex = prizes.findIndex(prize => prize.id === result.prize.id)
const spins = 5 + Math.random() * 3 // 5-8圈
const targetAngle = prizeIndex * segmentAngle + segmentAngle / 2
const finalRotation = rotation + (360 * spins) + (360 - targetAngle)
setRotation(finalRotation)
setSelectedPrize(selectedPrize)
// 动画结束后显示结果
setTimeout(() => {
setIsSpinning(false)
setShowResult(true)
onSpinComplete?.(selectedPrize)
}, 4000)
} catch (error) {
console.error('抽奖失败:', error)
setIsSpinning(false)
// 这里可以显示错误提示
alert(error instanceof Error ? error.message : '抽奖失败,请重试')
}
}
const createWheelPath = (index: number, totalSegments: number) => {
const angle = 360 / totalSegments
const startAngle = index * angle - 90
const endAngle = startAngle + angle
const startAngleRad = (startAngle * Math.PI) / 180
const endAngleRad = (endAngle * Math.PI) / 180
const largeArcFlag = angle > 180 ? 1 : 0
const x1 = 150 + 140 * Math.cos(startAngleRad)
const y1 = 150 + 140 * Math.sin(startAngleRad)
const x2 = 150 + 140 * Math.cos(endAngleRad)
const y2 = 150 + 140 * Math.sin(endAngleRad)
return `M 150 150 L ${x1} ${y1} A 140 140 0 ${largeArcFlag} 1 ${x2} ${y2} Z`
}
return (
<div className="flex flex-col items-center gap-6">
<Card className="w-full max-w-md">
<CardContent className="p-6">
<div className="relative">
{/* 转盘容器 */}
<div className="relative w-80 h-80 mx-auto">
{/* 装饰背景 */}
<div className="absolute inset-0 bg-gradient-to-br from-red-50 to-orange-50 rounded-full" />
{/* 转盘 */}
<div
ref={wheelRef}
className="absolute inset-4 transition-transform duration-[4000ms] ease-out"
style={{ transform: `rotate(${rotation}deg)` }}
>
<svg width="288" height="288" viewBox="0 0 300 300" className="w-full h-full">
{prizes.map((prize, index) => (
<g key={prize.id}>
<path
d={createWheelPath(index, prizes.length)}
fill={prize.color}
stroke="white"
strokeWidth="2"
/>
<text
x="150"
y="150"
fill="white"
fontSize="14"
fontWeight="bold"
textAnchor="middle"
dominantBaseline="middle"
transform={`rotate(${index * segmentAngle + segmentAngle / 2} 150 150) translate(0 -80)`}
>
{prize.name}
</text>
<text
x="150"
y="150"
fill="white"
fontSize="12"
textAnchor="middle"
dominantBaseline="middle"
transform={`rotate(${index * segmentAngle + segmentAngle / 2} 150 150) translate(0 -60)`}
>
{prize.remaining}
</text>
</g>
))}
</svg>
</div>
{/* 中心按钮 */}
<div className="absolute inset-0 flex items-center justify-center">
<Button
onClick={spinWheel}
disabled={isSpinning || disabled}
size="lg"
className="w-20 h-20 rounded-full bg-red-500 hover:bg-red-600 text-white font-bold text-lg shadow-lg disabled:opacity-50"
>
{isSpinning ? (
<RotateCw className="w-8 h-8 animate-spin" />
) : (
'GO'
)}
</Button>
</div>
{/* 指针 */}
<div className="absolute -top-4 left-1/2 transform -translate-x-1/2">
<div className="w-0 h-0 border-l-[20px] border-l-transparent border-r-[20px] border-r-transparent border-b-[40px] border-b-red-500" />
</div>
</div>
</div>
{/* 奖品列表 */}
<div className="mt-6 space-y-2">
<h3 className="font-semibold text-gray-900 text-center mb-3"></h3>
<div className="grid grid-cols-2 gap-2">
{prizes.map((prize) => (
<div key={prize.id} className="flex items-center gap-2 p-2 bg-gray-50 rounded-lg">
<div
className="w-4 h-4 rounded-full"
style={{ backgroundColor: prize.color }}
/>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-900 truncate">{prize.name}</p>
<p className="text-xs text-gray-500"> {prize.remaining}/{prize.total}</p>
</div>
</div>
))}
</div>
</div>
</CardContent>
</Card>
{/* 中奖结果弹窗 */}
<Dialog open={showResult} onOpenChange={setShowResult}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="text-center">
<div className="flex items-center justify-center gap-2">
<Sparkles className="w-6 h-6 text-yellow-500" />
</div>
</DialogTitle>
</DialogHeader>
{selectedPrize && (
<div className="text-center space-y-4">
<div className="w-20 h-20 mx-auto bg-gradient-to-br from-yellow-400 to-orange-500 rounded-full flex items-center justify-center">
<Gift className="w-10 h-10 text-white" />
</div>
<div>
<h3 className="text-xl font-bold text-gray-900">{selectedPrize.name}</h3>
<p className="text-gray-500 mt-1"></p>
</div>
<div className="flex gap-2 justify-center">
<Button variant="outline" onClick={() => setShowResult(false)}>
</Button>
<Button className="bg-red-500 hover:bg-red-600">
使
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}

View File

@ -0,0 +1,335 @@
'use client'
import { useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
Star,
Heart,
Send,
Bookmark,
ShoppingCart,
Eye,
TrendingUp
} from 'lucide-react'
interface ProductCardProps {
product: {
id: string
name: string
image: string
price: number
originalPrice: number
discount: string
rating: number
reviews: number
likes: number
comments: number
description: string
tags: string[]
stock: number
category: string
isHot?: boolean
isNew?: boolean
}
onLike: (id: string) => void
onBookmark: (id: string) => void
onShare: (title: string) => void
onPurchase: (id: string) => void
isLiked: boolean
isBookmarked: boolean
variant?: 'default' | 'compact' | 'featured'
}
export function ProductCard({
product,
onLike,
onBookmark,
onShare,
onPurchase,
isLiked,
isBookmarked,
variant = 'default'
}: ProductCardProps) {
const [isHovered, setIsHovered] = useState(false)
const [imageLoaded, setImageLoaded] = useState(false)
const discountPercentage = Math.round(((product.originalPrice - product.price) / product.originalPrice) * 100)
if (variant === 'compact') {
return (
<Card
className="group border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl overflow-hidden cursor-pointer transform hover:scale-[1.02]"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<div className="relative">
<div className="aspect-square overflow-hidden bg-gray-100">
<img
src={product.image}
alt={product.name}
className={`w-full h-full object-cover transition-all duration-500 ${
imageLoaded ? 'opacity-100 scale-100' : 'opacity-0 scale-110'
} ${isHovered ? 'scale-110' : 'scale-100'}`}
onLoad={() => setImageLoaded(true)}
/>
</div>
{/* 标签 */}
<div className="absolute top-2 left-2 flex flex-col gap-1">
{product.isHot && (
<Badge className="bg-red-500 text-white text-xs px-2 py-0.5 rounded-full flex items-center gap-1">
<TrendingUp className="w-3 h-3" />
</Badge>
)}
{product.isNew && (
<Badge className="bg-green-500 text-white text-xs px-2 py-0.5 rounded-full">
</Badge>
)}
{discountPercentage > 0 && (
<Badge className="bg-orange-500 text-white text-xs px-2 py-0.5 rounded-full">
-{discountPercentage}%
</Badge>
)}
</div>
{/* 快捷操作 */}
<div className={`absolute top-2 right-2 flex flex-col gap-2 transition-all duration-300 ${
isHovered ? 'opacity-100 translate-x-0' : 'opacity-0 translate-x-2'
}`}>
<Button
variant="ghost"
size="sm"
className="bg-white/90 backdrop-blur-sm text-gray-700 p-2 rounded-full shadow-sm hover:bg-white"
onClick={(e) => {
e.stopPropagation()
onLike(product.id)
}}
>
<Heart className={`w-4 h-4 ${isLiked ? 'fill-red-500 text-red-500' : ''}`} />
</Button>
<Button
variant="ghost"
size="sm"
className="bg-white/90 backdrop-blur-sm text-gray-700 p-2 rounded-full shadow-sm hover:bg-white"
onClick={(e) => {
e.stopPropagation()
onBookmark(product.id)
}}
>
<Bookmark className={`w-4 h-4 ${isBookmarked ? 'fill-blue-500 text-blue-500' : ''}`} />
</Button>
</div>
{/* 库存警告 */}
{product.stock <= 5 && (
<div className="absolute bottom-2 left-2">
<Badge className="bg-red-500/90 text-white text-xs px-2 py-0.5 rounded-full">
{product.stock}
</Badge>
</div>
)}
</div>
<CardContent className="p-3">
<h3 className="font-semibold text-sm mb-1 line-clamp-2 leading-tight">{product.name}</h3>
<div className="flex items-center gap-1 mb-2">
<Star className="w-3 h-3 text-yellow-500 fill-current" />
<span className="text-xs text-gray-600">{product.rating}</span>
<span className="text-xs text-gray-400">({product.reviews})</span>
</div>
<div className="flex items-baseline gap-2 mb-2">
<span className="text-lg font-bold text-red-500">¥{product.price}</span>
{product.originalPrice > product.price && (
<span className="text-xs text-gray-400 line-through">¥{product.originalPrice}</span>
)}
</div>
<Button
className="w-full h-8 text-xs bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600"
onClick={(e) => {
e.stopPropagation()
onPurchase(product.id)
}}
>
<ShoppingCart className="w-3 h-3 mr-1" />
</Button>
</CardContent>
</Card>
)
}
return (
<Card
className="group border-0 shadow-lg hover:shadow-2xl transition-all duration-500 rounded-3xl overflow-hidden cursor-pointer transform hover:scale-[1.01]"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* 图片区域 */}
<div className="relative">
<div className="aspect-[4/3] overflow-hidden bg-gradient-to-br from-gray-100 to-gray-200">
<img
src={product.image}
alt={product.name}
className={`w-full h-full object-cover transition-all duration-700 ${
imageLoaded ? 'opacity-100 scale-100' : 'opacity-0 scale-110'
} ${isHovered ? 'scale-110' : 'scale-100'}`}
onLoad={() => setImageLoaded(true)}
/>
{/* 渐变遮罩 */}
<div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent" />
</div>
{/* 标签区域 */}
<div className="absolute top-4 left-4 flex flex-wrap gap-2">
{product.isHot && (
<Badge className="bg-red-500/90 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full flex items-center gap-1 shadow-lg">
<TrendingUp className="w-3 h-3" />
</Badge>
)}
{product.isNew && (
<Badge className="bg-green-500/90 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full shadow-lg">
</Badge>
)}
{discountPercentage > 0 && (
<Badge className="bg-orange-500/90 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full shadow-lg">
-{discountPercentage}%
</Badge>
)}
</div>
{/* 快捷操作按钮 */}
<div className={`absolute top-4 right-4 flex gap-2 transition-all duration-300 ${
isHovered ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-2'
}`}>
<Button
variant="ghost"
size="sm"
className="bg-white/20 backdrop-blur-md text-white p-2.5 rounded-full shadow-lg hover:bg-white/30 transition-all duration-200"
onClick={(e) => {
e.stopPropagation()
onLike(product.id)
}}
>
<Heart className={`w-5 h-5 ${isLiked ? 'fill-current text-red-400' : ''}`} />
</Button>
<Button
variant="ghost"
size="sm"
className="bg-white/20 backdrop-blur-md text-white p-2.5 rounded-full shadow-lg hover:bg-white/30 transition-all duration-200"
onClick={(e) => {
e.stopPropagation()
onBookmark(product.id)
}}
>
<Bookmark className={`w-5 h-5 ${isBookmarked ? 'fill-current text-blue-400' : ''}`} />
</Button>
</div>
{/* 库存提醒 */}
{product.stock <= 5 && (
<div className="absolute bottom-4 left-4">
<Badge className="bg-red-500/90 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full shadow-lg animate-pulse">
{product.stock}
</Badge>
</div>
)}
{/* 查看详情按钮 */}
<div className={`absolute bottom-4 right-4 transition-all duration-300 ${
isHovered ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-2'
}`}>
<Button
variant="ghost"
size="sm"
className="bg-white/20 backdrop-blur-md text-white p-2.5 rounded-full shadow-lg hover:bg-white/30"
>
<Eye className="w-5 h-5" />
</Button>
</div>
</div>
<CardContent className="p-6">
<div className="space-y-4">
{/* 标题和描述 */}
<div>
<h3 className="font-bold text-xl mb-2 line-clamp-2 leading-tight">{product.name}</h3>
<p className="text-sm text-gray-600 line-clamp-2 leading-relaxed">{product.description}</p>
</div>
{/* 评分和评价 */}
<div className="flex items-center gap-4">
<div className="flex items-center gap-1">
<Star className="w-4 h-4 text-yellow-500 fill-current" />
<span className="font-semibold text-sm">{product.rating}</span>
</div>
<span className="text-sm text-gray-500">{product.reviews} </span>
<span className="text-sm text-gray-500"> {product.stock}</span>
</div>
{/* 价格区域 */}
<div className="flex items-baseline gap-3">
<span className="text-3xl font-bold text-red-500">¥{product.price}</span>
{product.originalPrice > product.price && (
<span className="text-lg text-gray-400 line-through">¥{product.originalPrice}</span>
)}
{discountPercentage > 0 && (
<Badge variant="secondary" className="text-sm font-semibold">
¥{product.originalPrice - product.price}
</Badge>
)}
</div>
{/* 互动区域 */}
<div className="flex items-center justify-between pt-4 border-t border-gray-100">
<div className="flex items-center gap-6">
<Button
variant="ghost"
size="sm"
className="flex items-center gap-2 text-gray-600 hover:text-red-500 transition-colors"
onClick={(e) => {
e.stopPropagation()
onLike(product.id)
}}
>
<Heart className={`w-5 h-5 ${isLiked ? 'fill-red-500 text-red-500' : ''}`} />
<span className="text-sm font-medium">{product.likes}</span>
</Button>
<Button
variant="ghost"
size="sm"
className="flex items-center gap-2 text-gray-600 hover:text-blue-500 transition-colors"
onClick={(e) => {
e.stopPropagation()
onShare(product.name)
}}
>
<Send className="w-5 h-5" />
<span className="text-sm font-medium">{product.comments}</span>
</Button>
</div>
<Button
className="px-8 py-2.5 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
onClick={(e) => {
e.stopPropagation()
onPurchase(product.id)
}}
>
<ShoppingCart className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
</CardContent>
</Card>
)
}

View File

@ -0,0 +1,154 @@
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Share2, Copy, QrCode, MessageCircle, Wechat } from 'lucide-react'
interface ShareDialogProps {
activity: {
id: string
title: string
description?: string
}
children: React.ReactNode
}
export default function ShareDialog({ activity, children }: ShareDialogProps) {
const [open, setOpen] = useState(false)
const [copied, setCopied] = useState(false)
const shareUrl = `${window.location.origin}/activity/${activity.id}`
const shareText = `快来参与「${activity.title}」抽奖活动!${activity.description || ''}`
const handleCopyLink = async () => {
try {
await navigator.clipboard.writeText(shareUrl)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('复制失败:', error)
}
}
const handleShareToWechat = () => {
// 这里可以集成微信分享SDK
alert('微信分享功能需要集成微信SDK')
}
const handleShareToWeibo = () => {
const weiboUrl = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(shareText)}`
window.open(weiboUrl, '_blank')
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Share2 className="w-5 h-5 text-red-500" />
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
{/* 活动信息 */}
<div className="p-3 bg-gray-50 rounded-lg">
<h3 className="font-semibold text-gray-900">{activity.title}</h3>
{activity.description && (
<p className="text-sm text-gray-600 mt-1">{activity.description}</p>
)}
</div>
{/* 分享链接 */}
<div>
<Label htmlFor="share-url"></Label>
<div className="flex gap-2 mt-1">
<Input
id="share-url"
value={shareUrl}
readOnly
className="flex-1"
/>
<Button
variant="outline"
size="sm"
onClick={handleCopyLink}
className="shrink-0"
>
{copied ? (
<span className="text-green-600"></span>
) : (
<>
<Copy className="w-4 h-4 mr-1" />
</>
)}
</Button>
</div>
</div>
{/* 分享文案 */}
<div>
<Label htmlFor="share-text"></Label>
<Textarea
id="share-text"
value={shareText}
readOnly
rows={3}
className="mt-1"
/>
</div>
{/* 分享渠道 */}
<div>
<Label></Label>
<div className="grid grid-cols-3 gap-2 mt-2">
<Button
variant="outline"
size="sm"
onClick={handleShareToWechat}
className="flex flex-col gap-1 h-auto py-3"
>
<Wechat className="w-5 h-5 text-green-500" />
<span className="text-xs"></span>
</Button>
<Button
variant="outline"
size="sm"
onClick={handleShareToWeibo}
className="flex flex-col gap-1 h-auto py-3"
>
<MessageCircle className="w-5 h-5 text-red-500" />
<span className="text-xs"></span>
</Button>
<Button
variant="outline"
size="sm"
className="flex flex-col gap-1 h-auto py-3"
>
<QrCode className="w-5 h-5 text-blue-500" />
<span className="text-xs"></span>
</Button>
</div>
</div>
{/* 分享统计 */}
<div className="pt-3 border-t">
<div className="flex items-center justify-between text-sm text-gray-500">
<span></span>
<Badge variant="secondary">0 </Badge>
</div>
</div>
</div>
</DialogContent>
</Dialog>
)
}

View File

@ -0,0 +1,621 @@
'use client'
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import {
Crown,
Star,
Gift,
Calendar,
Settings,
TrendingUp,
Target,
Award,
Sparkles,
Package,
Perfume
} from 'lucide-react'
export default function SubscriptionSystem() {
const [activeTab, setActiveTab] = useState('overview')
const [showSubscribeDialog, setShowSubscribeDialog] = useState(false)
const [selectedPlan, setSelectedPlan] = useState('')
const [deliveryFrequency, setDeliveryFrequency] = useState('monthly')
const [deliveryDay, setDeliveryDay] = useState('5')
const [excludedScents, setExcludedScents] = useState<string[]>([])
// 模拟用户数据
const userSubscription = {
plan: 'tasting',
status: 'active',
nextDelivery: '2025-04-05',
unlockedScents: ['玫瑰', '薰衣草', '茉莉'],
points: 1280,
level: '品鉴会员',
joinDate: '2025-01-15'
}
const membershipLevels = [
{
id: 'explore',
name: '探索会员',
icon: Star,
color: 'blue',
price: 99,
benefits: [
'盲盒95折优惠',
'月返5%积分',
'基础客服支持',
'每月1次退换货'
],
requirements: '无门槛'
},
{
id: 'tasting',
name: '品鉴会员',
icon: Crown,
color: 'purple',
price: 199,
benefits: [
'盲盒85折优惠',
'专属客服支持',
'分销订单奖10%积分',
'每月3次退换货',
'生日专属礼品'
],
requirements: '累计消费满500元'
},
{
id: 'perfumer',
name: '调香会员',
icon: Sparkles,
color: 'gold',
price: 399,
benefits: [
'免费调香咨询',
'新品优先试用',
'积分兑线下体验',
'专属调香师服务',
'无限次退换货',
'VIP专属活动'
],
requirements: '累计消费满2000元'
}
]
const pointHistory = [
{
id: '1',
type: 'earn',
amount: 50,
source: '拼团成功',
description: '参与玫瑰香水拼团成功',
time: '2025-04-02 14:30',
relatedId: 'group_buy_123'
},
{
id: '2',
type: 'earn',
amount: 100,
source: '分销奖励',
description: '好友完成首单购买',
time: '2025-04-01 10:15',
relatedId: 'order_456'
},
{
id: '3',
type: 'spend',
amount: -500,
source: '积分兑换',
description: '兑换¥50正装优惠券',
time: '2025-03-30 16:20',
relatedId: 'exchange_789'
},
{
id: '4',
type: 'earn',
amount: 200,
source: 'UGC内容',
description: '香氛评测被收录',
time: '2025-03-28 09:45',
relatedId: 'ugc_101'
}
]
const redemptionOptions = [
{
id: '1',
name: '¥50正装优惠券',
points: 500,
category: '优惠券',
stock: 100,
description: '全场正装商品可用有效期30天'
},
{
id: '2',
name: '调香师1v1咨询',
points: 1000,
category: '服务',
stock: 20,
description: '专业调香师一对一咨询服务时长60分钟'
},
{
id: '3',
name: '限定沙龙香体验',
points: 2000,
category: '体验',
stock: 10,
description: '线下沙龙香品鉴会,含专业讲解'
},
{
id: '4',
name: '生日专属礼盒',
points: 1500,
category: '礼品',
stock: 50,
description: '生日月专属定制香氛礼盒'
}
]
const scentOptions = [
{ id: 'rose', name: '玫瑰调', category: '花香调' },
{ id: 'lavender', name: '薰衣草', category: '草本调' },
{ id: 'jasmine', name: '茉莉', category: '花香调' },
{ id: 'sandalwood', name: '檀香', category: '木质调' },
{ id: 'citrus', name: '柑橘', category: '果香调' },
{ id: 'ocean', name: '海洋', category: '清新调' }
]
const handleSubscribe = () => {
// 处理订阅逻辑
console.log('订阅计划:', selectedPlan)
console.log('配送频率:', deliveryFrequency)
console.log('配送日期:', deliveryDay)
console.log('排除香型:', excludedScents)
setShowSubscribeDialog(false)
}
const handleRedeem = (option: any) => {
if (userSubscription.points >= option.points) {
// 处理积分兑换逻辑
console.log('兑换:', option.name)
} else {
alert('积分不足')
}
}
const currentLevel = membershipLevels.find(level => level.id === userSubscription.plan)
return (
<div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50 p-4">
<div className="max-w-6xl mx-auto">
{/* Header */}
<div className="bg-white rounded-lg shadow-sm p-6 mb-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
{currentLevel && <currentLevel.icon className="w-6 h-6 text-white" />}
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900"></h1>
<p className="text-gray-600">{userSubscription.level}</p>
</div>
</div>
<div className="flex items-center gap-6">
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="text-2xl font-bold text-purple-600">{userSubscription.points}</p>
</div>
<div className="text-center">
<p className="text-sm text-gray-600"></p>
<p className="text-lg font-bold text-green-600">{userSubscription.nextDelivery}</p>
</div>
<Button onClick={() => setShowSubscribeDialog(true)}>
<Settings className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="overview"></TabsTrigger>
<TabsTrigger value="points"></TabsTrigger>
<TabsTrigger value="subscription"></TabsTrigger>
<TabsTrigger value="benefits"></TabsTrigger>
</TabsList>
{/* 会员概览 */}
<TabsContent value="overview" className="mt-6">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* 当前会员等级 */}
<Card className="lg:col-span-2">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Crown className="w-5 h-5 text-purple-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4 mb-6">
<div className="w-16 h-16 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
{currentLevel && <currentLevel.icon className="w-8 h-8 text-white" />}
</div>
<div className="flex-1">
<h3 className="text-xl font-bold">{currentLevel?.name}</h3>
<p className="text-gray-600">{userSubscription.joinDate}</p>
<div className="flex items-center gap-2 mt-2">
<Badge className="bg-purple-100 text-purple-800"></Badge>
<Badge variant="outline"></Badge>
</div>
</div>
</div>
<div className="space-y-3">
<h4 className="font-semibold"></h4>
{currentLevel?.benefits.map((benefit, index) => (
<div key={index} className="flex items-center gap-2">
<Star className="w-4 h-4 text-yellow-500" />
<span className="text-sm">{benefit}</span>
</div>
))}
</div>
</CardContent>
</Card>
{/* 会员升级 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<TrendingUp className="w-5 h-5 text-green-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{membershipLevels
.filter(level => level.id !== userSubscription.plan)
.map((level) => (
<div key={level.id} className="border rounded-lg p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<level.icon className="w-4 h-4 text-gray-500" />
<span className="font-medium">{level.name}</span>
</div>
<span className="text-sm font-bold text-purple-600">¥{level.price}</span>
</div>
<p className="text-xs text-gray-600 mb-2">{level.requirements}</p>
<Button size="sm" variant="outline" className="w-full">
</Button>
</div>
))}
</div>
</CardContent>
</Card>
</div>
{/* 解锁香型 */}
<Card className="mt-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Perfume className="w-5 h-5 text-pink-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
{scentOptions.map((scent) => (
<div
key={scent.id}
className={`text-center p-3 rounded-lg border ${
userSubscription.unlockedScents.includes(scent.name)
? 'bg-purple-50 border-purple-200'
: 'bg-gray-50 border-gray-200'
}`}
>
<div className={`w-8 h-8 mx-auto mb-2 rounded-full ${
userSubscription.unlockedScents.includes(scent.name)
? 'bg-purple-500'
: 'bg-gray-300'
}`} />
<p className="text-sm font-medium">{scent.name}</p>
<p className="text-xs text-gray-500">{scent.category}</p>
{userSubscription.unlockedScents.includes(scent.name) && (
<Badge className="mt-1 text-xs"></Badge>
)}
</div>
))}
</div>
<div className="mt-4 p-3 bg-yellow-50 rounded-lg">
<p className="text-sm text-yellow-800">
💡 3
</p>
</div>
</CardContent>
</Card>
</TabsContent>
{/* 积分中心 */}
<TabsContent value="points" className="mt-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 积分历史 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3">
{pointHistory.map((record) => (
<div key={record.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium">{record.description}</span>
<Badge variant={record.type === 'earn' ? 'default' : 'secondary'}>
{record.type === 'earn' ? '获得' : '消费'}
</Badge>
</div>
<p className="text-xs text-gray-500">{record.source} · {record.time}</p>
</div>
<div className={`text-lg font-bold ${
record.type === 'earn' ? 'text-green-600' : 'text-red-600'
}`}>
{record.type === 'earn' ? '+' : ''}{record.amount}
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* 积分兑换 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{redemptionOptions.map((option) => (
<div key={option.id} className="border rounded-lg p-4">
<div className="flex items-center justify-between mb-2">
<h4 className="font-semibold">{option.name}</h4>
<Badge variant="outline">{option.category}</Badge>
</div>
<p className="text-sm text-gray-600 mb-3">{option.description}</p>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Gift className="w-4 h-4 text-purple-500" />
<span className="font-bold text-purple-600">{option.points} </span>
</div>
<Button
size="sm"
onClick={() => handleRedeem(option)}
disabled={userSubscription.points < option.points}
>
{userSubscription.points >= option.points ? '立即兑换' : '积分不足'}
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</TabsContent>
{/* 订阅管理 */}
<TabsContent value="subscription" className="mt-6">
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<h4 className="font-semibold mb-3"></h4>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-gray-600"></span>
<span className="font-medium">{currentLevel?.name}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600"></span>
<Badge className="bg-green-100 text-green-800"></Badge>
</div>
<div className="flex justify-between">
<span className="text-gray-600"></span>
<span className="font-medium">{userSubscription.nextDelivery}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600"></span>
<span className="font-medium">5</span>
</div>
</div>
</div>
<div>
<h4 className="font-semibold mb-3"></h4>
<div className="space-y-3">
<div>
<Label htmlFor="frequency"></Label>
<Select value={deliveryFrequency} onValueChange={setDeliveryFrequency}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly"></SelectItem>
<SelectItem value="semimonthly"></SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="delivery-day"></Label>
<Select value={deliveryDay} onValueChange={setDeliveryDay}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="15">15</SelectItem>
</SelectContent>
</Select>
</div>
<Button className="w-full"></Button>
</div>
</div>
</div>
</CardContent>
</Card>
</TabsContent>
{/* 会员权益 */}
<TabsContent value="benefits" className="mt-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{membershipLevels.map((level) => (
<Card key={level.id} className={`relative ${
level.id === userSubscription.plan ? 'ring-2 ring-purple-500' : ''
}`}>
{level.id === userSubscription.plan && (
<div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
<Badge className="bg-purple-500 text-white"></Badge>
</div>
)}
<CardHeader className="text-center">
<div className="w-12 h-12 mx-auto mb-2 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
<level.icon className="w-6 h-6 text-white" />
</div>
<CardTitle className="text-xl">{level.name}</CardTitle>
<p className="text-sm text-gray-600">{level.requirements}</p>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="text-center">
<span className="text-2xl font-bold text-purple-600">¥{level.price}</span>
<span className="text-gray-500">/</span>
</div>
<div className="space-y-2">
{level.benefits.map((benefit, index) => (
<div key={index} className="flex items-center gap-2">
<Star className="w-4 h-4 text-yellow-500" />
<span className="text-sm">{benefit}</span>
</div>
))}
</div>
{level.id !== userSubscription.plan && (
<Button
className="w-full mt-4"
variant={level.id === 'tasting' ? 'default' : 'outline'}
>
{level.id === 'explore' ? '立即订阅' : '升级会员'}
</Button>
)}
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
</Tabs>
{/* 订阅对话框 */}
<Dialog open={showSubscribeDialog} onOpenChange={setShowSubscribeDialog}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="plan"></Label>
<Select value={selectedPlan} onValueChange={setSelectedPlan}>
<SelectTrigger>
<SelectValue placeholder="选择订阅计划" />
</SelectTrigger>
<SelectContent>
{membershipLevels.map((level) => (
<SelectItem key={level.id} value={level.id}>
{level.name} - ¥{level.price}/
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="frequency"></Label>
<Select value={deliveryFrequency} onValueChange={setDeliveryFrequency}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly"></SelectItem>
<SelectItem value="semimonthly"></SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="delivery-day"></Label>
<Select value={deliveryDay} onValueChange={setDeliveryDay}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="15">15</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label></Label>
<div className="grid grid-cols-2 gap-2 mt-2">
{scentOptions.map((scent) => (
<div key={scent.id} className="flex items-center space-x-2">
<Checkbox
id={scent.id}
checked={excludedScents.includes(scent.name)}
onCheckedChange={(checked) => {
if (checked) {
setExcludedScents([...excludedScents, scent.name])
} else {
setExcludedScents(excludedScents.filter(name => name !== scent.name))
}
}}
/>
<Label htmlFor={scent.id} className="text-sm">{scent.name}</Label>
</div>
))}
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={() => setShowSubscribeDialog(false)} className="flex-1">
</Button>
<Button onClick={handleSubscribe} className="flex-1">
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
</div>
)
}

View File

@ -0,0 +1,66 @@
"use client"
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 }

View File

@ -0,0 +1,157 @@
"use client"
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,
}

View File

@ -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 }

View File

@ -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 }

View File

@ -0,0 +1,53 @@
"use client"
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 }

View File

@ -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-md 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 }

View File

@ -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,
}

View File

@ -0,0 +1,59 @@
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 shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs 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 shadow-xs 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",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@ -0,0 +1,213 @@
"use client"
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import { DayButton, DayPicker, getDefaultClassNames } 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 [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
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 }

View File

@ -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-1.5 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,
}

View File

@ -0,0 +1,241 @@
"use client"
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,
}

353
src/components/ui/chart.tsx Normal file
View File

@ -0,0 +1,353 @@
"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.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.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,
}

View File

@ -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="flex items-center justify-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@ -0,0 +1,33 @@
"use client"
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 }

View File

@ -0,0 +1,184 @@
"use client"
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,
}

View File

@ -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 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,
}

View File

@ -0,0 +1,143 @@
"use client"
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 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,
}

View File

@ -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,
}

View File

@ -0,0 +1,257 @@
"use client"
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 flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
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,
}

167
src/components/ui/form.tsx Normal file
View File

@ -0,0 +1,167 @@
"use client"
import * as React from "react"
import * 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,
}

View File

@ -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 }

View File

@ -0,0 +1,77 @@
"use client"
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 }

View File

@ -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 flex 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 }

View File

@ -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 }

View File

@ -0,0 +1,276 @@
"use client"
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,
}

View File

@ -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,
}

View File

@ -0,0 +1,127 @@
import * as React from "react"
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
)
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />
}
type PaginationLinkProps = {
isActive?: boolean
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
{...props}
>
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
)
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
{...props}
>
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
)
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
)
}
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}

View File

@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-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-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
}
export { Progress }

View File

@ -0,0 +1,45 @@
"use client"
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
)
}
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-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 dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator
data-slot="radio-group-indicator"
className="relative flex items-center justify-center"
>
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
}
export { RadioGroup, RadioGroupItem }

View File

@ -0,0 +1,56 @@
"use client"
import * as React from "react"
import { GripVerticalIcon } from "lucide-react"
import * as ResizablePrimitive from "react-resizable-panels"
import { cn } from "@/lib/utils"
function ResizablePanelGroup({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) {
return (
<ResizablePrimitive.PanelGroup
data-slot="resizable-panel-group"
className={cn(
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
className
)}
{...props}
/>
)
}
function ResizablePanel({
...props
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
}
function ResizableHandle({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean
}) {
return (
<ResizablePrimitive.PanelResizeHandle
data-slot="resizable-handle"
className={cn(
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className
)}
{...props}
>
{withHandle && (
<div className="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
<GripVerticalIcon className="size-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
)
}
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }

View File

@ -0,0 +1,58 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
function ScrollArea({
className,
children,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
<ScrollAreaPrimitive.ScrollAreaScrollbar
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
data-slot="scroll-area-thumb"
className="bg-border relative flex-1 rounded-full"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
)
}
export { ScrollArea, ScrollBar }

View File

@ -0,0 +1,185 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "popper",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 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 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

139
src/components/ui/sheet.tsx Normal file
View File

@ -0,0 +1,139 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-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 SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary 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">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@ -0,0 +1,726 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, VariantProps } from "class-variance-authority"
import { PanelLeftIcon } from "lucide-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className
)}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
)
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
)}
{...props}
/>
)
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
)
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
)
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
)
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
)
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

View File

@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@ -0,0 +1,63 @@
"use client"
import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"
import { cn } from "@/lib/utils"
function Slider({
className,
defaultValue,
value,
min = 0,
max = 100,
...props
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
const _values = React.useMemo(
() =>
Array.isArray(value)
? value
: Array.isArray(defaultValue)
? defaultValue
: [min, max],
[value, defaultValue, min, max]
)
return (
<SliderPrimitive.Root
data-slot="slider"
defaultValue={defaultValue}
value={value}
min={min}
max={max}
className={cn(
"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
className
)}
{...props}
>
<SliderPrimitive.Track
data-slot="slider-track"
className={cn(
"bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
)}
>
<SliderPrimitive.Range
data-slot="slider-range"
className={cn(
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
)}
/>
</SliderPrimitive.Track>
{Array.from({ length: _values.length }, (_, index) => (
<SliderPrimitive.Thumb
data-slot="slider-thumb"
key={index}
className="border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
/>
))}
</SliderPrimitive.Root>
)
}
export { Slider }

View File

@ -0,0 +1,25 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner, ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }

View File

@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as SwitchPrimitive from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
function Switch({
className,
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitive.Root>
)
}
export { Switch }

116
src/components/ui/table.tsx Normal file
View File

@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@ -0,0 +1,66 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
function Tabs({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function TabsList({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
className
)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent }

View File

@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

129
src/components/ui/toast.tsx Normal file
View File

@ -0,0 +1,129 @@
"use client"
import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}

View File

@ -0,0 +1,35 @@
"use client"
import { useToast } from "@/hooks/use-toast"
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

View File

@ -0,0 +1,73 @@
"use client"
import * as React from "react"
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
>({
size: "default",
variant: "default",
})
function ToggleGroup({
className,
variant,
size,
children,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
className={cn(
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
className
)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
)
}
function ToggleGroupItem({
className,
children,
variant,
size,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext)
return (
<ToggleGroupPrimitive.Item
data-slot="toggle-group-item"
data-variant={context.variant || variant}
data-size={context.size || size}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
className
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
)
}
export { ToggleGroup, ToggleGroupItem }

View File

@ -0,0 +1,47 @@
"use client"
import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-9 px-2 min-w-9",
sm: "h-8 px-1.5 min-w-8",
lg: "h-10 px-2.5 min-w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Toggle({
className,
variant,
size,
...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Toggle, toggleVariants }

View File

@ -0,0 +1,61 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

19
src/hooks/use-mobile.ts Normal file
View File

@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

194
src/hooks/use-toast.ts Normal file
View File

@ -0,0 +1,194 @@
"use client"
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

13
src/lib/db.ts Normal file
View File

@ -0,0 +1,13 @@
import { PrismaClient } from '@prisma/client'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
export const db =
globalForPrisma.prisma ??
new PrismaClient({
log: ['query'],
})
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db

29
src/lib/socket.ts Normal file
View File

@ -0,0 +1,29 @@
import { Server } from 'socket.io';
export const setupSocket = (io: Server) => {
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
// Handle messages
socket.on('message', (msg: { text: string; senderId: string }) => {
// Echo: broadcast message only the client who send the message
socket.emit('message', {
text: `Echo: ${msg.text}`,
senderId: 'system',
timestamp: new Date().toISOString(),
});
});
// Handle disconnect
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
});
// Send welcome message
socket.emit('message', {
text: 'Welcome to WebSocket Echo Server!',
senderId: 'system',
timestamp: new Date().toISOString(),
});
});
};

30
src/lib/toast-utils.ts Normal file
View File

@ -0,0 +1,30 @@
import { toast } from '@/hooks/use-toast'
export const showSuccessToast = (message: string) => {
toast({
title: "成功",
description: message,
})
}
export const showErrorToast = (message: string) => {
toast({
title: "错误",
description: message,
variant: "destructive",
})
}
export const showLikeToast = () => {
toast({
title: "已点赞",
description: "您已为这个内容点赞",
})
}
export const showShareToast = () => {
toast({
title: "分享成功",
description: "链接已复制到剪贴板",
})
}

6
src/lib/utils.ts Normal file
View File

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

64
tailwind.config.ts Normal file
View File

@ -0,0 +1,64 @@
import type { Config } from "tailwindcss";
import tailwindcssAnimate from "tailwindcss-animate";
const config: Config = {
darkMode: "class",
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))'
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))'
},
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))'
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))'
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))'
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))'
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))'
},
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
chart: {
'1': 'hsl(var(--chart-1))',
'2': 'hsl(var(--chart-2))',
'3': 'hsl(var(--chart-3))',
'4': 'hsl(var(--chart-4))',
'5': 'hsl(var(--chart-5))'
}
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
}
}
},
plugins: [tailwindcssAnimate],
};
export default config;

28
tsconfig.json Normal file
View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"noImplicitAny": false,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}