init
Some checks failed
CI/CD / Backend & Frontend Checks (push) Has been cancelled
CI/CD / Deploy to Production (push) Has been cancelled

This commit is contained in:
2026-05-18 11:34:07 +03:30
commit 7a8ddeabed
279 changed files with 37390 additions and 0 deletions

24
frontend/.gitignore vendored Normal file
View File

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

32
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,32 @@
FROM node:20-alpine AS builder
WORKDIR /app
# Accept build argument for API base URL
ARG NEXT_PUBLIC_API_BASE
ENV NEXT_PUBLIC_API_BASE=${NEXT_PUBLIC_API_BASE}
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy source code
COPY . .
# Build the application
RUN npm run build
# Production image
FROM nginx:alpine
# Copy built files to nginx
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy nginx configuration
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

36
frontend/README.md Normal file
View File

@@ -0,0 +1,36 @@
# Frontend
## Stack
- Vite + React 18 with TypeScript.
- `@tanstack/react-query` for data fetching and caching.
- shadcn/ui primitives (button, card, tabs, dialog, etc.) with Tailwind CSS.
- Sonner & Toast UI for notifications, Markdown rendering, RTL layout, and Persian-digit helpers.
## Development
### Install dependencies
```bash
npm install
```
### Run dev server
```bash
npm run dev -- --host
```
### Production build
```bash
npm run build
```
## Features
- **Public site**: homepage, events list/detail, blog list, auth flows, profile, payments.
- **Admin dashboard**: staff-only portal with vertical tabs, user filtering, event filtering, popup detail with registrations/payments, and inline event editing/deletion.
- **Utils**: Persian digit formatting, price conversion (Rial → Toman), shared API client with JWT token refresh handling, and helper components (scroll area, table, dialog).
## Testing & linting
```bash
npm run lint
```
JavaScript/TypeScript linting is configured through ESLint + `typescript-eslint`. Run lint before commits to keep code healthy.

BIN
frontend/bun.lockb Normal file

Binary file not shown.

20
frontend/components.json Normal file
View File

@@ -0,0 +1,20 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "src/index.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}

26
frontend/eslint.config.js Normal file
View File

@@ -0,0 +1,26 @@
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"@typescript-eslint/no-unused-vars": "off",
},
},
);

22
frontend/index.html Normal file
View File

@@ -0,0 +1,22 @@
<!doctype html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<title>انجمن علمی کامپیوتر گیلان - Guilan ACE</title>
<meta name="description" content="انجمن علمی دانشجویی کامپیوتر دانشگاه گیلان" />
<meta name="author" content="Guilan ACE" />
<meta property="og:title" content="انجمن علمی کامپیوتر گیلان" />
<meta property="og:description" content="انجمن علمی دانشجویی کامپیوتر دانشگاه گیلان" />
<meta property="og:type" content="website" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

33
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,33 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Enable gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# Handle Next.js static export
location / {
try_files $uri $uri.html $uri/ /index.html;
}
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Disable access to hidden files
location ~ /\. {
deny all;
}
}

8556
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

91
frontend/package.json Normal file
View File

@@ -0,0 +1,91 @@
{
"name": "vite_react_shadcn_ts",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"build:dev": "vite build --mode development",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@hookform/resolvers": "^3.10.0",
"@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",
"@tanstack/react-query": "^5.83.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-helmet-async": "^2.0.5",
"react-hook-form": "^7.61.1",
"react-markdown": "^9.0.3",
"react-resizable-panels": "^2.1.9",
"react-router-dom": "^6.30.1",
"recharts": "^2.15.4",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.9",
"zod": "^3.25.76",
"react-qr-code": "^2.0.11",
"jspdf": "^2.5.1",
"html2canvas": "^1.4.1"
},
"devDependencies": {
"@eslint/js": "^9.32.0",
"@tailwindcss/typography": "^0.5.16",
"@types/node": "^22.16.5",
"@types/react": "^18.3.26",
"@types/react-dom": "^18.3.7",
"@vitejs/plugin-react-swc": "^3.11.0",
"autoprefixer": "^10.4.21",
"eslint": "^9.32.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^15.15.0",
"lovable-tagger": "^1.1.10",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "^5.8.3",
"typescript-eslint": "^8.38.0",
"vite": "^5.4.19"
}
}

View File

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

BIN
frontend/public/enamad.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1200" fill="none"><rect width="1200" height="1200" fill="#EAEAEA" rx="3"/><g opacity=".5"><g opacity=".5"><path fill="#FAFAFA" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/></g><path stroke="url(#a)" stroke-width="2.418" d="M0-1.209h553.581" transform="scale(1 -1) rotate(45 1163.11 91.165)"/><path stroke="url(#b)" stroke-width="2.418" d="M404.846 598.671h391.726"/><path stroke="url(#c)" stroke-width="2.418" d="M599.5 795.742V404.017"/><path stroke="url(#d)" stroke-width="2.418" d="m795.717 796.597-391.441-391.44"/><path fill="#fff" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/><g clip-path="url(#e)"><path fill="#666" fill-rule="evenodd" d="M616.426 586.58h-31.434v16.176l3.553-3.554.531-.531h9.068l.074-.074 8.463-8.463h2.565l7.18 7.181V586.58Zm-15.715 14.654 3.698 3.699 1.283 1.282-2.565 2.565-1.282-1.283-5.2-5.199h-6.066l-5.514 5.514-.073.073v2.876a2.418 2.418 0 0 0 2.418 2.418h26.598a2.418 2.418 0 0 0 2.418-2.418v-8.317l-8.463-8.463-7.181 7.181-.071.072Zm-19.347 5.442v4.085a6.045 6.045 0 0 0 6.046 6.045h26.598a6.044 6.044 0 0 0 6.045-6.045v-7.108l1.356-1.355-1.282-1.283-.074-.073v-17.989h-38.689v23.43l-.146.146.146.147Z" clip-rule="evenodd"/></g><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/></g><defs><linearGradient id="a" x1="554.061" x2="-.48" y1=".083" y2=".087" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="b" x1="796.912" x2="404.507" y1="599.963" y2="599.965" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="c" x1="600.792" x2="600.794" y1="403.677" y2="796.082" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="d" x1="404.85" x2="796.972" y1="403.903" y2="796.02" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><clipPath id="e"><path fill="#fff" d="M581.364 580.535h38.689v38.689h-38.689z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

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: /

42
frontend/src/App.css Normal file
View File

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

72
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,72 @@
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { HelmetProvider } from "react-helmet-async";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import Layout from "@/components/Layout";
import { AuthProvider } from "@/contexts/AuthContext";
import AdminLayout from "@/pages/AdminLayout";
import AdminUsers from "@/pages/AdminUsers";
import AdminEvents from "@/pages/AdminEvents";
import AdminEventEdit from "@/pages/AdminEventEdit";
import AdminEventDetail from "@/pages/AdminEventDetail";
import AboutUs from "@/pages/AboutUs";
import Auth from "@/pages/Auth";
import Blog from "@/pages/Blog";
import EventDetail from "@/pages/EventDetail";
import EventFreeSuccessPage from "@/pages/EventFreeSuccessPage";
import Events from "@/pages/Events";
import Home from "@/pages/Home";
import Logout from "@/pages/Logout";
import NotFound from "@/pages/NotFound";
import PaymentResult from "@/pages/PaymentResult";
import Profile from "@/pages/Profile";
import ResetPasswordConfirm from "@/pages/ResetPasswordConfirm";
import ResetPasswordRequest from "@/pages/ResetPasswordRequest";
import VerifyEmail from "@/pages/VerifyEmail";
const queryClient = new QueryClient();
const App = () => (
<QueryClientProvider client={queryClient}>
<AuthProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<HelmetProvider>
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="auth" element={<Auth />} />
<Route path="logout" element={<Logout />} />
<Route path="profile" element={<Profile />} />
<Route path="blog" element={<Blog />} />
<Route path="events" element={<Events />} />
<Route path="events/:slug" element={<EventDetail />} />
<Route path="events/:slug/success" element={<EventFreeSuccessPage />} />
<Route path="payments/result" element={<PaymentResult />} />
<Route path="verify-email/:token" element={<VerifyEmail />} />
<Route path="reset-password" element={<ResetPasswordRequest />} />
<Route path="reset-password/:token" element={<ResetPasswordConfirm />} />
<Route path="/about" element={<AboutUs />} />
<Route path="/admin" element={<AdminLayout />}>
<Route index element={<Navigate to="/admin/users" replace />} />
<Route path="users" element={<AdminUsers />} />
<Route path="events" element={<AdminEvents />} />
<Route path="events/:id" element={<AdminEventDetail />} />
<Route path="events/:id/edit" element={<AdminEventEdit />} />
</Route>
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
</HelmetProvider>
</TooltipProvider>
</AuthProvider>
</QueryClientProvider>
);
export default App;

View File

@@ -0,0 +1,136 @@
import * as React from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn, formatNumberPersian, formatToman, resolveErrorMessage } from "@/lib/utils";
type RawVerifyResult = {
discount_amount: number;
final_price: number;
};
type Normalized = {
valid: boolean;
discount_amount: number;
final_price: number;
message_fa: string;
};
type Props = {
open: boolean;
onOpenChange: (v: boolean) => void;
basePrice: number; // مبلغ اولیه رویداد
onVerifyCouponRaw: (code: string) => Promise<RawVerifyResult>;
onContinue: (coupon?: string, finalPrice?: number) => void; // ادامه‌ی جریان ثبت‌نام/پرداخت
};
export default function CouponDialogFa({
open,
onOpenChange,
basePrice,
onVerifyCouponRaw,
onContinue,
}: Props) {
const [code, setCode] = React.useState("");
const [verifying, setVerifying] = React.useState(false);
const [res, setRes] = React.useState<Normalized | null>(null);
// اگر نتیجه نداریم، قیمت نهایی = قیمت پایه
const finalPrice = res?.final_price ?? basePrice / 10;
const handleVerify = async () => {
if (!code) return;
try {
setVerifying(true);
// فراخوانی تابع خام که فقط خروجی بک‌اند را می‌دهد
const raw = await onVerifyCouponRaw(code);
// --- نرمالایز داخل همین کامپوننت ---
setRes({
valid: true,
discount_amount: (raw.discount_amount ?? 0) / 10,
final_price: (raw.final_price ?? basePrice) / 10,
message_fa: "کد تخفیف با موفقیت اعمال شد",
});
} catch (error) {
setRes({
valid: false,
discount_amount: 0,
final_price: basePrice / 10, // برگرداندن قیمت به حالت اولیه
message_fa: resolveErrorMessage(error, "کد تخفیف معتبر نیست"),
});
} finally {
setVerifying(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md" dir="rtl">
<DialogHeader>
<DialogTitle>کد تخفیف</DialogTitle>
</DialogHeader>
<div className="grid gap-4 text-right">
<div className="grid gap-2">
<Label htmlFor="coupon">کد تخفیف (اختیاری)</Label>
<div className="flex gap-2">
<Input
id="coupon"
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="مثلاً OFF20"
className="text-right"
/>
<Button variant="secondary" disabled={!code || verifying} onClick={handleVerify}>
{verifying ? "در حال بررسی..." : "بررسی کد"}
</Button>
</div>
{/* پیام زیر اینپوت: موفق/نامعتبر */}
{res && (
<p className={cn("text-sm", res.valid ? "text-emerald-600" : "text-destructive")}>
{res.message_fa}
</p>
)}
</div>
<div className="rounded-md border p-3 space-y-1">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">قیمت اولیه</span>
<span className="font-medium">{formatToman(basePrice)}</span>
</div>
{res?.discount_amount ? (
<div className="flex items-center justify-between">
<span className="text-muted-foreground">تخفیف</span>
<span className="font-medium">
- {formatNumberPersian(res.discount_amount)} تومان
</span>
</div>
) : null}
<div className="flex items-center justify-between border-t pt-2">
<span className="text-muted-foreground">قیمت نهایی</span>
<span className="font-semibold">{formatNumberPersian(finalPrice)} تومان</span>
</div>
</div>
</div>
<DialogFooter className="sm:justify-start">
<div className="flex w-full items-center justify-end gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>انصراف</Button>
<Button
onClick={() => onContinue(code || undefined, finalPrice)}
disabled={verifying /* در حال بررسی که هستیم، ادامه غیرفعال باشد */}
>
ادامه و پرداخت
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,157 @@
import * as React from "react";
import { Link } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { Instagram, Send, Twitter, Linkedin } from "lucide-react";
import { api } from "@/lib/api"; // متد subscribeNewsletter را پایین توضیح داده‌ام
export default function Footer() {
// const { toast } = useToast();
// const [email, setEmail] = React.useState("");
// const [loading, setLoading] = React.useState(false);
const year = new Date().getFullYear();
// const validateEmail = (v: string) =>
// /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());
// const onSubmit = async (e: React.FormEvent) => {
// e.preventDefault();
// const em = email.trim();
// if (!validateEmail(em)) {
// toast({ title: "ایمیل نامعتبر است", description: "لطفاً یک ایمیل صحیح وارد کنید.", variant: "destructive" });
// return;
// }
// try {
// setLoading(true);
// const response = await api.subscribeNewsletter(em);
// if (response.success) {
// toast({ title: "عضویت موفق", description: response.message });
// setEmail("");
// } else {
// toast({ title: "عضویت ناموفق", description: response.message, variant: "destructive" });
// }
// } catch (err: any) {
// toast({ title: "خطا", description: err?.message || "مشکلی رخ داد.", variant: "destructive" });
// } finally {
// setLoading(false);
// }
// };
return (
<footer className="border-t bg-background/60 backdrop-blur supports-[backdrop-filter]:bg-background/40" dir="rtl">
<div className="container mx-auto px-4 py-10">
<div className="grid gap-8 md:grid-cols-2 lg:grid-cols-4">
{/* برند + درباره + اینماد */}
<div className="space-y-4">
<div className="flex items-center gap-2">
<img src="/favicon.ico" alt="لوگوی انجمن" className="h-9 w-9 rounded" />
<span className="text-xl font-bold">انجمن علمی کامپیوتر گیلان</span>
</div>
<p className="text-sm text-muted-foreground leading-7">
ترویج علم کامپیوتر، برگزاری رویدادهای تخصصی، تقویت شبکهٔ دانشجویی و پیوند با صنعت.
</p>
</div>
{/* لینک‌های سریع */}
<div>
<h4 className="mb-3 text-base font-semibold">لینکهای مفید</h4>
<ul className="space-y-2 text-sm">
<li><Link to="/" className="text-muted-foreground hover:text-foreground">خانه</Link></li>
<li><Link to="/events" className="text-muted-foreground hover:text-foreground">رویدادها</Link></li>
<li><Link to="/blog" className="text-muted-foreground hover:text-foreground">بلاگ</Link></li>
<li><Link to="/about" className="text-muted-foreground hover:text-foreground">دربارهٔ انجمن</Link></li>
{/* <li><Link to="/contact" className="text-muted-foreground hover:text-foreground">تماس با ما</Link></li> */}
{/* <li><Link to="/rules" className="text-muted-foreground hover:text-foreground">قوانین و حریم خصوصی</Link></li> */}
</ul>
</div>
{/* اطلاعات تماس / شبکه‌های اجتماعی */}
<div>
<h4 className="mb-3 text-base font-semibold">ارتباط با ما</h4>
<ul className="space-y-2 text-sm text-muted-foreground">
<li>ایمیل: info@east-guilan-ce.ir</li>
<li>آدرس: دانشگاه گیلان، دانشکدهی فنی و مهندسی شرق گیلان</li>
</ul>
<div className="mt-4 flex items-center gap-2">
<a href="https://Instagram.com/guilance.ir" target="_blank" rel="noreferrer" className="inline-flex">
<Button variant="outline" size="icon" className="h-9 w-9" aria-label="اینستاگرام">
<Instagram className="h-4 w-4" />
</Button>
</a>
<a href="https://t.me/guilance" target="_blank" rel="noreferrer" className="inline-flex">
<Button variant="outline" size="icon" className="h-9 w-9" aria-label="تلگرام">
<Send className="h-4 w-4" />
</Button>
</a>
<a href="https://www.linkedin.com/in/amiirkhl/" target="_blank" rel="noreferrer" className="inline-flex">
<Button variant="outline" size="icon" className="h-9 w-9" aria-label="لینکدین">
<Linkedin className="h-4 w-4" />
</Button>
</a>
<a href="https://x.com" target="_blank" rel="noreferrer" className="inline-flex">
<Button variant="outline" size="icon" className="h-9 w-9" aria-label="ایکس (توییتر)">
<Twitter className="h-4 w-4" />
</Button>
</a>
</div>
</div>
{/* خبرنامه */}
{/* <div>
<h4 className="mb-3 text-base font-semibold">عضویت در خبرنامه</h4>
<p className="mb-3 text-sm text-muted-foreground">
برای اطلاع از رویدادها و اخبار انجمن، ایمیل خود را وارد کنید.
</p>
<form onSubmit={onSubmit} className="flex flex-col sm:flex-row gap-2">
<Input
type="email"
inputMode="email"
placeholder="ایمیل شما"
dir="ltr"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="sm:flex-1 text-left"
/>
<Button type="submit" disabled={loading}>
{loading ? "در حال عضویت..." : "عضویت"}
</Button>
</form>
<p className="mt-2 text-xs text-muted-foreground">
با عضویت، با <Link to="/rules" className="underline underline-offset-4">قوانین و حریم خصوصی</Link> موافقم.
</p>
</div> */}
<div className="justify-self-end">
<a
href="https://trustseal.enamad.ir/?id=649977&Code=m0wWM1DFYqd4fLEnjyMU3o2pupfuqDVW"
target="_blank"
rel="noreferrer"
referrerPolicy="origin"
>
<img
src="/enamad.png"
width="125px"
alt="نماد اعتماد الکترونیکی"
referrerPolicy="origin"
style={{ cursor: "pointer" }}
data-code="m0wWM1DFYqd4fLEnjyMU3o2pupfuqDVW"
/>
</a>
</div>
</div>
{/* خط جداکننده */}
<div className="my-8 h-px w-full bg-border" />
{/* کپی‌رایت */}
<div className="flex gap-2 items-center justify-center text-sm text-muted-foreground md:flex-row">
<div>© {year} انجمن علمی کامپیوتر گیلان تمامی حقوق محفوظ است.</div>
</div>
</div>
</footer>
);
}

View File

@@ -0,0 +1,15 @@
import { Outlet } from 'react-router-dom';
import Navbar from './Navbar';
import Footer from './Footer';
import ScrollToTop from './ScrollToTop';
export default function Layout() {
return (
<div className="min-h-screen">
<ScrollToTop onlyOnPush={false} smooth={false} />
<Navbar />
<Outlet />
<Footer />
</div>
);
}

View File

@@ -0,0 +1,110 @@
import React from 'react';
import ReactMarkdown from 'react-markdown';
import type { PluggableList } from 'unified';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize from 'rehype-sanitize';
type MarkdownSize = 'sm' | 'base' | 'lg';
type MarkdownProps = {
content?: string;
allowHtml?: boolean;
className?: string;
dir?: 'rtl' | 'ltr';
justify?: boolean;
size?: MarkdownSize;
};
export default function Markdown({
content = '',
allowHtml = false,
className = '',
dir = 'rtl',
justify = false,
size = 'sm',
}: MarkdownProps) {
const rehypePlugins: PluggableList | undefined = allowHtml ? [rehypeRaw, rehypeSanitize] : undefined;
const baseSizeClass =
size === 'sm' ? 'text-sm' : size === 'lg' ? 'text-lg' : 'text-base';
const hScale =
size === 'sm'
? { h1: 'text-xl', h2: 'text-lg', h3: 'text-base', h4: 'text-base' }
: size === 'base'
? { h1: 'text-3xl', h2: 'text-2xl', h3: 'text-xl', h4: 'text-lg' }
: { h1: 'text-4xl', h2: 'text-3xl', h3: 'text-2xl', h4: 'text-xl' };
const justifyStyle: React.CSSProperties | undefined = justify
? { textAlign: 'justify', textJustify: 'inter-word' }
: undefined;
return (
<div
dir={dir}
className={`markdown-body ${baseSizeClass} text-right leading-7 break-words ${className}`}
style={justifyStyle}
>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={rehypePlugins}
components={{
h1: (p) => <h1 className={`mt-6 font-bold ${hScale.h1}`} {...p} />,
h2: (p) => <h2 className={`mt-6 font-bold ${hScale.h2}`} {...p} />,
h3: (p) => <h3 className={`mt-5 font-semibold ${hScale.h3}`} {...p} />,
h4: (p) => <h4 className={`mt-4 font-semibold ${hScale.h4}`} {...p} />,
p: (p) => <p className="my-3" {...p} />,
a: (p) => <a className="underline decoration-primary hover:opacity-90 break-all" target="_blank" rel="noopener noreferrer" {...p} />,
ul: (p) => <ul className="my-3 list-disc ps-6 space-y-1.5" {...p} />,
ol: (p) => <ol className="my-3 list-decimal ps-6 space-y-1.5" {...p} />,
li: (p) => <li className="[&>ul]:my-1.5 [&>ol]:my-1.5" {...p} />,
hr: (p) => <hr className="my-5 border-muted" {...p} />,
blockquote: (p) => (
<blockquote className="my-3 border-r-4 pr-4 italic text-muted-foreground" {...p} />
),
code: ({ className, children, node, ...p }) => {
const isInline =
node?.tagName === 'code' &&
!/language-/.test(className || '') &&
!String(children).includes('\n');
if (isInline) {
return (
<code className="rounded bg-muted px-1 py-0.5 text-[0.9em]" {...p}>
{children}
</code>
);
}
return (
<code className={className} {...p}>
{children}
</code>
);
},
pre: ({ className = '', children, ...p }) => (
<pre
className={[
"my-4 overflow-x-auto rounded-md bg-muted p-4 text-[0.9em]",
className,
].filter(Boolean).join(" ")}
{...p}
>
{children}
</pre>
),
table: (p) => (
<div className="my-3 overflow-x-auto">
<table className="w-full border-collapse" {...p} />
</div>
),
th: (p) => <th className="border-b p-2 text-right font-semibold" {...p} />,
td: (p) => <td className="border-b p-2 align-top" {...p} />,
}}
>
{content}
</ReactMarkdown>
</div>
);
}

View File

@@ -0,0 +1,40 @@
// src/components/ModeToggle.tsx
import { Button } from '@/components/ui/button';
import { Moon, Sun } from 'lucide-react';
import { useTheme } from '@/components/ThemeProvider';
export default function ModeToggle() {
const { theme, setTheme } = useTheme();
const handleToggle = () => {
if (theme === 'system' && typeof window !== 'undefined') {
const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
setTheme(prefersDark ? 'light' : 'dark');
return;
}
setTheme(theme === 'dark' ? 'light' : 'dark');
};
const isDark =
theme === 'dark' ||
(theme === 'system' &&
typeof document !== 'undefined' &&
document.documentElement.classList.contains('dark'));
const nextThemeLabel = isDark ? 'روشن' : 'تاریک';
return (
<Button
variant="outline"
size="icon"
aria-label={`تغییر تم به حالت ${nextThemeLabel}`}
title={`تغییر تم به حالت ${nextThemeLabel}`}
onClick={handleToggle}
>
<Sun className="h-5 w-5 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-5 w-5 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
);
}

View File

@@ -0,0 +1,205 @@
import { useMemo, useState } from 'react';
import { Link, NavLink, useNavigate } from 'react-router-dom';
import { Menu, ChevronDown } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import ModeToggle from '@/components/ModeToggle';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
const NavItem = ({
to,
children,
onClick,
}: {
to: string;
children: React.ReactNode;
onClick?: () => void;
}) => (
<NavLink
to={to}
onClick={onClick}
className={({ isActive }) =>
[
'px-2 py-1 rounded-md transition-colors',
isActive ? 'text-primary' : 'text-muted-foreground hover:text-foreground',
].join(' ')
}
>
{children}
</NavLink>
);
export default function Navbar() {
const navigate = useNavigate();
const { user, isAuthenticated } = useAuth();
const isAdminUser = isAuthenticated && ((user?.is_staff || user?.is_superuser) ?? false);
const [open, setOpen] = useState(false);
const avatarInitials = useMemo(
() => (user?.first_name?.[0] || user?.last_name?.[0] || user?.username?.[0] || '?').toUpperCase(),
[user?.first_name, user?.last_name, user?.username],
);
const UserDropdown = () => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex items-center gap-2 rounded-full border border-border/60 bg-muted/40 px-2 py-1 pr-2.5 transition hover:bg-muted"
>
<Avatar className="h-9 w-9">
<AvatarImage src={user?.profile_picture || undefined} alt={user?.username || 'profile'} />
<AvatarFallback>{avatarInitials}</AvatarFallback>
</Avatar>
<ChevronDown className="h-4 w-4 text-muted-foreground" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56" dir="rtl">
<DropdownMenuLabel className="text-xs text-muted-foreground">
{user?.first_name || user?.last_name ? `${user?.first_name || ''} ${user?.last_name || ''}`.trim() : user?.username}
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link to="/profile">پروفایل</Link>
</DropdownMenuItem>
{isAdminUser && (
<DropdownMenuItem asChild>
<Link to="/admin">داشبورد مدیریت</Link>
</DropdownMenuItem>
)}
<DropdownMenuItem
onSelect={(e) => e.preventDefault()}
className="flex items-center justify-between gap-2"
>
<span>حالت نمایش</span>
<ModeToggle />
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
navigate('/logout');
}}
className="text-red-600 focus:text-red-600"
>
خروج
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
return (
<nav className="sticky top-0 z-40 border-b bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/60" dir="rtl">
<div className="container mx-auto px-4 py-3">
<div className="flex flex-row-reverse items-center justify-between gap-3">
<Link to="/" className="order-2 flex items-center gap-2">
<span className="sm:inline text-2xl font-bold text-primary">
انجمن علمی کامپیوتر گیلان
</span>
</Link>
<div className="order-1 hidden md:flex items-center gap-2">
<NavItem to="/">خانه</NavItem>
<NavItem to="/blog">بلاگ</NavItem>
<NavItem to="/events">رویدادها</NavItem>
{isAuthenticated ? (
<UserDropdown />
) : (
<>
<Link to="/auth">
<Button size="sm">ورود / ثبتنام</Button>
</Link>
<ModeToggle />
</>
)}
</div>
<div className="order-1 md:hidden">
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button variant="outline" size="icon" aria-label="U.U+U^">
<Menu className="h-5 w-5" />
</Button>
</SheetTrigger>
<SheetContent side="right" className="w-[80vw] sm:w-[360px]" dir="rtl">
<div className="mt-6 flex flex-col gap-4 text-right">
<Link
to="/"
onClick={() => setOpen(false)}
className="flex items-center gap-2"
>
<img src="/favicon.ico" alt="لوگو" className="h-8 w-auto" height={32} width={32} />
<span className="text-xl font-semibold text-primary">انجمن علمی کامپیوتر گیلان</span>
</Link>
<div className="grid gap-2">
<NavItem to="/" onClick={() => setOpen(false)}>خانه</NavItem>
<NavItem to="/blog" onClick={() => setOpen(false)}>بلاگ</NavItem>
<NavItem to="/events" onClick={() => setOpen(false)}>رویدادها</NavItem>
</div>
<div className="pt-4 border-t grid gap-3">
{isAuthenticated ? (
<>
<div className="flex items-center gap-3 rounded-md border px-3 py-2">
<Avatar className="h-10 w-10">
<AvatarImage src={user?.profile_picture || undefined} alt={user?.username || 'profile'} />
<AvatarFallback>{avatarInitials}</AvatarFallback>
</Avatar>
<div className="flex-1 text-right">
<div className="font-medium">{user?.username}</div>
{user?.email ? <div className="text-xs text-muted-foreground">{user.email}</div> : null}
</div>
</div>
<div className="grid gap-2">
<Button variant="ghost" className="justify-between" asChild onClick={() => setOpen(false)}>
<Link to="/profile">پروفایل</Link>
</Button>
{isAdminUser && (
<Button variant="ghost" className="justify-between" asChild onClick={() => setOpen(false)}>
<Link to="/admin">داشبورد مدیریت</Link>
</Button>
)}
<div className="flex items-center justify-between rounded-md border px-3 py-2">
<span className="text-sm text-muted-foreground">حالت نمایش</span>
<ModeToggle />
</div>
<Button
variant="outline"
className="justify-between text-red-600 border-red-600 hover:bg-red-50 dark:text-red-400 dark:border-red-400 dark:hover:bg-red-950/30"
onClick={() => { setOpen(false); navigate('/logout'); }}
>
خروج
</Button>
</div>
</>
) : (
<div className="grid gap-2">
<Link to="/auth" onClick={() => setOpen(false)}>
<Button className="w-full">ورود / ثبتنام</Button>
</Link>
<div className="flex items-center justify-between rounded-md border px-3 py-2">
<span className="text-sm text-muted-foreground">حالت نمایش</span>
<ModeToggle />
</div>
</div>
)}
</div>
</div>
</SheetContent>
</Sheet>
</div>
</div>
</div>
</nav>
);
}

View File

@@ -0,0 +1,48 @@
import * as React from "react";
type PaymentResultProps = {
title: string;
subtitle?: string;
details?: Array<{ label: string; value: React.ReactNode }>;
className?: string;
};
export default function PaymentResult({
title,
subtitle,
details,
className,
}: PaymentResultProps) {
return (
<div
className={[
"mx-auto max-w-xl rounded-2xl border border-border bg-card text-card-foreground shadow-sm",
"transition-colors",
className,
].join(" ")}
>
<div className="p-6">
<h1 className="text-2xl font-semibold leading-tight">{title}</h1>
{subtitle && (
<p className="mt-2 text-sm text-muted-foreground">{subtitle}</p>
)}
{details?.length ? (
<ul className="mt-6 divide-y divide-border/60">
{details.map((d, i) => (
<li
key={i}
className="flex items-start justify-between gap-4 py-3"
>
<span className="text-sm text-muted-foreground">{d.label}</span>
<span className="font-medium text-right text-foreground break-words">
{d.value}
</span>
</li>
))}
</ul>
) : null}
</div>
</div>
);
}

View File

@@ -0,0 +1,36 @@
import * as React from "react";
import { useLocation, useNavigationType } from "react-router-dom";
export default function ScrollToTop({
onlyOnPush = false, // if true, keeps scroll on back/forward (POP)
smooth = false, // smooth animation
}: { onlyOnPush?: boolean; smooth?: boolean }) {
const { pathname, hash } = useLocation();
const navType = useNavigationType(); // 'PUSH' | 'POP' | 'REPLACE'
React.useLayoutEffect(() => {
// If URL has a hash (#id), scroll to that element
if (hash) {
const el = document.getElementById(hash.slice(1));
if (el) {
el.scrollIntoView({ behavior: smooth ? "smooth" : "auto", block: "start" });
return;
}
}
// If you want to keep scroll when user hits back/forward:
if (onlyOnPush && navType === "POP") return;
window.scrollTo({ top: 0, left: 0, behavior: smooth ? "smooth" : "auto" });
}, [pathname, hash, navType, onlyOnPush, smooth]);
// Disable native restoration if you always want to control it
React.useEffect(() => {
if (!onlyOnPush && "scrollRestoration" in window.history) {
const prev = window.history.scrollRestoration;
window.history.scrollRestoration = "manual";
return () => { window.history.scrollRestoration = prev as "auto" | "manual"; };
}
}, [onlyOnPush]);
return null;
}

View File

@@ -0,0 +1,92 @@
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import { Check, ChevronsUpDown } from "lucide-react";
type Item = { value: string; label: string };
type Props = {
items: Item[];
value: string | null;
onChange: (v: string | null) => void;
placeholder?: string;
searchPlaceholder?: string;
emptyText?: string;
className?: string;
disabled?: boolean;
dir?: "rtl" | "ltr";
};
export default function SearchableCombobox({
items,
value,
onChange,
placeholder = "انتخاب کنید…",
searchPlaceholder = "جستجو...",
emptyText = "چیزی پیدا نشد",
className,
disabled,
dir = "rtl",
}: Props) {
const [open, setOpen] = React.useState(false);
const selected = items.find((i) => String(i.value) === String(value)) || null;
const join = (...xs: (string | undefined | false)[]) => xs.filter(Boolean).join(" ");
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled}
className={join("w-full justify-between", className)}
>
{selected ? selected.label : placeholder}
<ChevronsUpDown className="h-4 w-4 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
side="bottom"
className="w-[--radix-popover-trigger-width] p-0"
dir={dir}
>
<Command dir={dir}>
<CommandInput placeholder={searchPlaceholder} autoFocus />
<CommandList>
<CommandEmpty>{emptyText}</CommandEmpty>
<CommandGroup>
{items.map((i) => {
const active = selected?.value === i.value;
return (
<CommandItem
key={i.value}
value={i.label} // ← فیلتر روی متن لیبل انجام می‌شود
onSelect={() => {
onChange(i.value);
setOpen(false);
}}
>
<Check className={join("mr-2 h-4 w-4", active ? "opacity-100" : "opacity-0")} />
{i.label}
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}

View File

@@ -0,0 +1,56 @@
/* eslint-disable react-refresh/only-export-components */
import * as React from 'react';
type Theme = 'light' | 'dark' | 'system';
type Ctx = { theme: Theme; setTheme: (t: Theme) => void };
const ThemeContext = React.createContext<Ctx | null>(null);
export function ThemeProvider({
children,
defaultTheme = 'system',
storageKey = 'egce-theme',
}: {
children: React.ReactNode;
defaultTheme?: Theme;
storageKey?: string;
}) {
const [theme, setTheme] = React.useState<Theme>(() => {
try { return (localStorage.getItem(storageKey) as Theme) || defaultTheme; }
catch { return defaultTheme; }
});
React.useEffect(() => {
const root = document.documentElement;
const mql = window.matchMedia('(prefers-color-scheme: dark)');
const apply = (t: Theme) => {
const isDark = t === 'system' ? mql.matches : t === 'dark';
root.classList.toggle('dark', isDark);
};
apply(theme);
const onChange = () => theme === 'system' && apply('system');
mql.addEventListener('change', onChange);
return () => mql.removeEventListener('change', onChange);
}, [theme]);
React.useEffect(() => {
try {
localStorage.setItem(storageKey, theme);
} catch (error) {
console.warn('Unable to persist theme preference', error);
}
}, [theme, storageKey]);
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const ctx = React.useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
return ctx;
}

View File

@@ -0,0 +1,52 @@
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item ref={ref} className={cn("border-b", className)} {...props} />
));
AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
className,
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };

View File

@@ -0,0 +1,104 @@
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";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@@ -0,0 +1,43 @@
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 p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} />
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h5 ref={ref} className={cn("mb-1 font-medium leading-none tracking-tight", className)} {...props} />
),
);
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} {...props} />
),
);
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };

View File

@@ -0,0 +1,5 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };

View File

@@ -0,0 +1,38 @@
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/lib/utils";
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
{...props}
/>
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image ref={ref} className={cn("aspect-square h-full w-full", className)} {...props} />
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className)}
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };

View File

@@ -0,0 +1,30 @@
/* eslint-disable react-refresh/only-export-components */
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,90 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode;
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);
Breadcrumb.displayName = "Breadcrumb";
const BreadcrumbList = React.forwardRef<HTMLOListElement, React.ComponentPropsWithoutRef<"ol">>(
({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className,
)}
{...props}
/>
),
);
BreadcrumbList.displayName = "BreadcrumbList";
const BreadcrumbItem = React.forwardRef<HTMLLIElement, React.ComponentPropsWithoutRef<"li">>(
({ className, ...props }, ref) => (
<li ref={ref} className={cn("inline-flex items-center gap-1.5", className)} {...props} />
),
);
BreadcrumbItem.displayName = "BreadcrumbItem";
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean;
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a";
return <Comp ref={ref} className={cn("transition-colors hover:text-foreground", className)} {...props} />;
});
BreadcrumbLink.displayName = "BreadcrumbLink";
const BreadcrumbPage = React.forwardRef<HTMLSpanElement, React.ComponentPropsWithoutRef<"span">>(
({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
),
);
BreadcrumbPage.displayName = "BreadcrumbPage";
const BreadcrumbSeparator = ({ children, className, ...props }: React.ComponentProps<"li">) => (
<li role="presentation" aria-hidden="true" className={cn("[&>svg]:size-3.5", className)} {...props}>
{children ?? <ChevronRight />}
</li>
);
BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
const BreadcrumbEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
);
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};

View File

@@ -0,0 +1,48 @@
/* eslint-disable react-refresh/only-export-components */
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 ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
},
);
Button.displayName = "Button";
export { Button, buttonVariants };

View File

@@ -0,0 +1,54 @@
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
function Calendar({ className, classNames, showOutsideDays = true, ...props }: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
day: cn(buttonVariants({ variant: "ghost" }), "h-9 w-9 p-0 font-normal aria-selected:opacity-100"),
day_range_end: "day-range-end",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ ..._props }) => <ChevronLeft className="h-4 w-4" />,
IconRight: ({ ..._props }) => <ChevronRight className="h-4 w-4" />,
}}
{...props}
/>
);
}
Calendar.displayName = "Calendar";
export { Calendar };

View File

@@ -0,0 +1,43 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
),
);
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-tight", className)} {...props} />
),
);
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
),
);
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />,
);
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
),
);
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };

View File

@@ -0,0 +1,224 @@
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;
}
const Carousel = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & CarouselProps>(
({ orientation = "horizontal", opts, setApi, plugins, className, children, ...props }, ref) => {
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
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
},
);
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel();
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className)}
{...props}
/>
</div>
);
},
);
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const { orientation } = useCarousel();
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn("min-w-0 shrink-0 grow-0 basis-full", orientation === "horizontal" ? "pl-4" : "pt-4", className)}
{...props}
/>
);
},
);
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef<HTMLButtonElement, React.ComponentProps<typeof Button>>(
({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
);
},
);
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef<HTMLButtonElement, React.ComponentProps<typeof Button>>(
({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
);
},
);
CarouselNext.displayName = "CarouselNext";
export { type CarouselApi, Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext };

View File

@@ -0,0 +1,303 @@
import * as React from "react";
import * as RechartsPrimitive from "recharts";
import { cn, formatNumberPersian } 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;
}
const ChartContainer = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
config: ChartConfig;
children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>["children"];
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
return (
<ChartContext.Provider value={{ config }}>
<div
data-chart={chartId}
ref={ref}
className={cn(
"flex aspect-video justify-center text-xs [&_.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-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.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 [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",
className,
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
);
});
ChartContainer.displayName = "Chart";
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;
const ChartTooltipContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: "line" | "dot" | "dashed";
nameKey?: string;
labelKey?: string;
}
>(
(
{
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
},
ref,
) => {
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
ref={ref}
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background 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(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
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 !== undefined && item.value !== null && (
<span className="font-mono font-medium tabular-nums text-foreground">
{formatNumberPersian(Number(item.value))}
</span>
)}
</div>
</>
)}
</div>
);
})}
</div>
</div>
);
},
);
ChartTooltipContent.displayName = "ChartTooltip";
const ChartLegend = RechartsPrimitive.Legend;
const ChartLegendContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean;
nameKey?: string;
}
>(({ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey }, ref) => {
const { config } = useChart();
if (!payload?.length) {
return null;
}
return (
<div
ref={ref}
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("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground")}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
);
})}
</div>
);
});
ChartLegendContent.displayName = "ChartLegend";
// 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,26 @@
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };

View File

@@ -0,0 +1,9 @@
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };

View File

@@ -0,0 +1,132 @@
import * as React from "react";
import { type DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils";
import { Dialog, DialogContent } from "@/components/ui/dialog";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className,
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
type CommandDialogProps = DialogProps;
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[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>
);
};
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => <CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm" {...props} />);
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className,
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator ref={ref} className={cn("-mx-1 h-px bg-border", className)} {...props} />
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
className,
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)} {...props} />;
};
CommandShortcut.displayName = "CommandShortcut";
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};

View File

@@ -0,0 +1,178 @@
import * as React from "react";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const ContextMenu = ContextMenuPrimitive.Root;
const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
const ContextMenuGroup = ContextMenuPrimitive.Group;
const ContextMenuPortal = ContextMenuPrimitive.Portal;
const ContextMenuSub = ContextMenuPrimitive.Sub;
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
));
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",
className,
)}
{...props}
/>
));
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 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",
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
));
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
/>
));
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
));
ContextMenuCheckboxItem.displayName = ContextMenuPrimitive.CheckboxItem.displayName;
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
));
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold text-foreground", inset && "pl-8", className)}
{...props}
/>
));
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-border", className)} {...props} />
));
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
const ContextMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)} {...props} />;
};
ContextMenuShortcut.displayName = "ContextMenuShortcut";
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
};

View File

@@ -0,0 +1,95 @@
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

View File

@@ -0,0 +1,87 @@
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils";
const Drawer = ({ shouldScaleBackground = true, ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root shouldScaleBackground={shouldScaleBackground} {...props} />
);
Drawer.displayName = "Drawer";
const DrawerTrigger = DrawerPrimitive.Trigger;
const DrawerPortal = DrawerPrimitive.Portal;
const DrawerClose = DrawerPrimitive.Close;
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay ref={ref} className={cn("fixed inset-0 z-50 bg-black/80", className)} {...props} />
));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className,
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
));
DrawerContent.displayName = "DrawerContent";
const DrawerHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)} {...props} />
);
DrawerHeader.displayName = "DrawerHeader";
const DrawerFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />
);
DrawerFooter.displayName = "DrawerFooter";
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};

View File

@@ -0,0 +1,179 @@
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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",
className,
)}
{...props}
/>
));
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} />;
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};

View File

@@ -0,0 +1,130 @@
/* eslint-disable react-refresh/only-export-components */
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import { Controller, ControllerProps, FieldPath, FieldValues, FormProvider, useFormContext } 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, formState } = useFormContext();
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);
const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
);
},
);
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return <Label ref={ref} className={cn(error && "text-destructive", className)} htmlFor={formItemId} {...props} />;
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef<React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot>>(
({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
aria-invalid={!!error}
{...props}
/>
);
},
);
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return <p ref={ref} id={formDescriptionId} className={cn("text-sm text-muted-foreground", className)} {...props} />;
},
);
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
if (!body) {
return null;
}
return (
<p ref={ref} id={formMessageId} className={cn("text-sm font-medium text-destructive", className)} {...props}>
{body}
</p>
);
},
);
FormMessage.displayName = "FormMessage";
export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField };

View File

@@ -0,0 +1,27 @@
import * as React from "react";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { cn } from "@/lib/utils";
const HoverCard = HoverCardPrimitive.Root;
const HoverCardTrigger = HoverCardPrimitive.Trigger;
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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",
className,
)}
{...props}
/>
));
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;
export { HoverCard, HoverCardTrigger, HoverCardContent };

View File

@@ -0,0 +1,61 @@
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { Dot } from "lucide-react";
import { cn } from "@/lib/utils";
const InputOTP = React.forwardRef<React.ElementRef<typeof OTPInput>, React.ComponentPropsWithoutRef<typeof OTPInput>>(
({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn("flex items-center gap-2 has-[:disabled]:opacity-50", containerClassName)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
),
);
InputOTP.displayName = "InputOTP";
const InputOTPGroup = React.forwardRef<React.ElementRef<"div">, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => <div ref={ref} className={cn("flex items-center", className)} {...props} />,
);
InputOTPGroup.displayName = "InputOTPGroup";
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index];
return (
<div
ref={ref}
className={cn(
"relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-2 ring-ring ring-offset-background",
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink h-4 w-px bg-foreground duration-1000" />
</div>
)}
</div>
);
});
InputOTPSlot.displayName = "InputOTPSlot";
const InputOTPSeparator = React.forwardRef<React.ElementRef<"div">, React.ComponentPropsWithoutRef<"div">>(
({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Dot />
</div>
),
);
InputOTPSeparator.displayName = "InputOTPSeparator";
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

View File

@@ -0,0 +1,22 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Input.displayName = "Input";
export { Input };

View File

@@ -0,0 +1,17 @@
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const labelVariants = cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70");
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };

View File

@@ -0,0 +1,207 @@
import * as React from "react";
import * as MenubarPrimitive from "@radix-ui/react-menubar";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const MenubarMenu = MenubarPrimitive.Menu;
const MenubarGroup = MenubarPrimitive.Group;
const MenubarPortal = MenubarPrimitive.Portal;
const MenubarSub = MenubarPrimitive.Sub;
const MenubarRadioGroup = MenubarPrimitive.RadioGroup;
const Menubar = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Root
ref={ref}
className={cn("flex h-10 items-center space-x-1 rounded-md border bg-background p-1", className)}
{...props}
/>
));
Menubar.displayName = MenubarPrimitive.Root.displayName;
const MenubarTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Trigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
/>
));
MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName;
const MenubarSubTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<MenubarPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
));
MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName;
const MenubarSubContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 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",
className,
)}
{...props}
/>
));
MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName;
const MenubarContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>
>(({ className, align = "start", alignOffset = -4, sideOffset = 8, ...props }, ref) => (
<MenubarPrimitive.Portal>
<MenubarPrimitive.Content
ref={ref}
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",
className,
)}
{...props}
/>
</MenubarPrimitive.Portal>
));
MenubarContent.displayName = MenubarPrimitive.Content.displayName;
const MenubarItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
/>
));
MenubarItem.displayName = MenubarPrimitive.Item.displayName;
const MenubarCheckboxItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<MenubarPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
));
MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName;
const MenubarRadioItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<MenubarPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
));
MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName;
const MenubarLabel = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
{...props}
/>
));
MenubarLabel.displayName = MenubarPrimitive.Label.displayName;
const MenubarSeparator = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
));
MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName;
const MenubarShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)} {...props} />;
};
MenubarShortcut.displayname = "MenubarShortcut";
export {
Menubar,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarItem,
MenubarSeparator,
MenubarLabel,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarPortal,
MenubarSubContent,
MenubarSubTrigger,
MenubarGroup,
MenubarSub,
MenubarShortcut,
};

View File

@@ -0,0 +1,121 @@
/* eslint-disable react-refresh/only-export-components */
import * as React from "react";
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu";
import { cva } from "class-variance-authority";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn("relative z-10 flex max-w-max flex-1 items-center justify-center", className)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
));
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName;
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn("group flex flex-1 list-none items-center justify-center space-x-1", className)}
{...props}
/>
));
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName;
const NavigationMenuItem = NavigationMenuPrimitive.Item;
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50",
);
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDown
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
));
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName;
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
"left-0 top-0 w-full 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 md:absolute md:w-auto",
className,
)}
{...props}
/>
));
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName;
const NavigationMenuLink = NavigationMenuPrimitive.Link;
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn("absolute left-0 top-full flex justify-center")}>
<NavigationMenuPrimitive.Viewport
className={cn(
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
className,
)}
ref={ref}
{...props}
/>
</div>
));
NavigationMenuViewport.displayName = NavigationMenuPrimitive.Viewport.displayName;
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
className,
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
</NavigationMenuPrimitive.Indicator>
));
NavigationMenuIndicator.displayName = NavigationMenuPrimitive.Indicator.displayName;
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
};

View File

@@ -0,0 +1,81 @@
import * as React from "react";
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
import { ButtonProps, buttonVariants } from "@/components/ui/button";
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
role="navigation"
aria-label="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
);
Pagination.displayName = "Pagination";
const PaginationContent = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(
({ className, ...props }, ref) => (
<ul ref={ref} className={cn("flex flex-row items-center gap-1", className)} {...props} />
),
);
PaginationContent.displayName = "PaginationContent";
const PaginationItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ className, ...props }, ref) => (
<li ref={ref} className={cn("", className)} {...props} />
));
PaginationItem.displayName = "PaginationItem";
type PaginationLinkProps = {
isActive?: boolean;
} & Pick<ButtonProps, "size"> &
React.ComponentProps<"a">;
const PaginationLink = ({ className, isActive, size = "icon", ...props }: PaginationLinkProps) => (
<a
aria-current={isActive ? "page" : undefined}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className,
)}
{...props}
/>
);
PaginationLink.displayName = "PaginationLink";
const PaginationPrevious = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to previous page" size="default" className={cn("gap-1 pl-2.5", className)} {...props}>
<ChevronLeft className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
);
PaginationPrevious.displayName = "PaginationPrevious";
const PaginationNext = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to next page" size="default" className={cn("gap-1 pr-2.5", className)} {...props}>
<span>Next</span>
<ChevronRight className="h-4 w-4" />
</PaginationLink>
);
PaginationNext.displayName = "PaginationNext";
const PaginationEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => (
<span aria-hidden className={cn("flex h-9 w-9 items-center justify-center", className)} {...props}>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
);
PaginationEllipsis.displayName = "PaginationEllipsis";
export {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
};

View File

@@ -0,0 +1,29 @@
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent };

View File

@@ -0,0 +1,23 @@
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/lib/utils";
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn("relative h-4 w-full overflow-hidden rounded-full bg-secondary", className)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;
export { Progress };

View File

@@ -0,0 +1,36 @@
import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return <RadioGroupPrimitive.Root className={cn("grid gap-2", className)} {...props} ref={ref} />;
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };

View File

@@ -0,0 +1,37 @@
import { GripVertical } from "lucide-react";
import * as ResizablePrimitive from "react-resizable-panels";
import { cn } from "@/lib/utils";
const ResizablePanelGroup = ({ className, ...props }: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col", className)}
{...props}
/>
);
const ResizablePanel = ResizablePrimitive.Panel;
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 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-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className,
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };

View File

@@ -0,0 +1,38 @@
import * as React from "react";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { cn } from "@/lib/utils";
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props}>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
));
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent p-[1px]",
className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
export { ScrollArea, ScrollBar };

View File

@@ -0,0 +1,143 @@
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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",
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)]",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label ref={ref} className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)} {...props} />
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};

View File

@@ -0,0 +1,20 @@
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "@/lib/utils";
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = "horizontal", decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn("shrink-0 bg-border", orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", className)}
{...props}
/>
));
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };

View File

@@ -0,0 +1,107 @@
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const Sheet = SheetPrimitive.Root;
const SheetTrigger = SheetPrimitive.Trigger;
const SheetClose = SheetPrimitive.Close;
const SheetPortal = SheetPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
},
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<React.ElementRef<typeof SheetPrimitive.Content>, SheetContentProps>(
({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
),
);
SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
SheetHeader.displayName = "SheetHeader";
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
SheetFooter.displayName = "SheetFooter";
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title ref={ref} className={cn("text-lg font-semibold text-foreground", className)} {...props} />
));
SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetOverlay,
SheetPortal,
SheetTitle,
SheetTrigger,
};

View File

@@ -0,0 +1,638 @@
/* eslint-disable react-refresh/only-export-components */
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { VariantProps, cva } from "class-variance-authority";
import { PanelLeft } 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 } 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 SidebarContext = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContext | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
const SidebarProvider = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
>(({ defaultOpen = true, open: openProp, onOpenChange: setOpenProp, className, style, children, ...props }, ref) => {
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<SidebarContext>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar", className)}
ref={ref}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
);
});
SidebarProvider.displayName = "SidebarProvider";
const Sidebar = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}
>(({ side = "left", variant = "sidebar", collapsible = "offcanvas", className, children, ...props }, ref) => {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
className={cn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground", className)}
ref={ref}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-mobile="true"
className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
ref={ref}
className="group peer hidden text-sidebar-foreground md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
>
{/* This is what handles the sidebar gap on desktop */}
<div
className={cn(
"relative h-svh 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)_+_theme(spacing.4))]"
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon]",
)}
/>
<div
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)_+_theme(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"
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
>
{children}
</div>
</div>
</div>
);
});
Sidebar.displayName = "Sidebar";
const SidebarTrigger = React.forwardRef<React.ElementRef<typeof Button>, React.ComponentProps<typeof Button>>(
({ className, onClick, ...props }, ref) => {
const { toggleSidebar } = useSidebar();
return (
<Button
ref={ref}
data-sidebar="trigger"
variant="ghost"
size="icon"
className={cn("h-7 w-7", className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeft />
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
},
);
SidebarTrigger.displayName = "SidebarTrigger";
const SidebarRail = React.forwardRef<HTMLButtonElement, React.ComponentProps<"button">>(
({ className, ...props }, ref) => {
const { toggleSidebar } = useSidebar();
return (
<button
ref={ref}
data-sidebar="rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 hover:after:bg-sidebar-border sm:flex",
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
)}
{...props}
/>
);
},
);
SidebarRail.displayName = "SidebarRail";
const SidebarInset = React.forwardRef<HTMLDivElement, React.ComponentProps<"main">>(({ className, ...props }, ref) => {
return (
<main
ref={ref}
className={cn(
"relative flex min-h-svh flex-1 flex-col bg-background",
"peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
className,
)}
{...props}
/>
);
});
SidebarInset.displayName = "SidebarInset";
const SidebarInput = React.forwardRef<React.ElementRef<typeof Input>, React.ComponentProps<typeof Input>>(
({ className, ...props }, ref) => {
return (
<Input
ref={ref}
data-sidebar="input"
className={cn(
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
className,
)}
{...props}
/>
);
},
);
SidebarInput.displayName = "SidebarInput";
const SidebarHeader = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return <div ref={ref} data-sidebar="header" className={cn("flex flex-col gap-2 p-2", className)} {...props} />;
});
SidebarHeader.displayName = "SidebarHeader";
const SidebarFooter = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return <div ref={ref} data-sidebar="footer" className={cn("flex flex-col gap-2 p-2", className)} {...props} />;
});
SidebarFooter.displayName = "SidebarFooter";
const SidebarSeparator = React.forwardRef<React.ElementRef<typeof Separator>, React.ComponentProps<typeof Separator>>(
({ className, ...props }, ref) => {
return (
<Separator
ref={ref}
data-sidebar="separator"
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
);
},
);
SidebarSeparator.displayName = "SidebarSeparator";
const SidebarContent = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
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}
/>
);
});
SidebarContent.displayName = "SidebarContent";
const SidebarGroup = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
});
SidebarGroup.displayName = "SidebarGroup";
const SidebarGroupLabel = React.forwardRef<HTMLDivElement, React.ComponentProps<"div"> & { asChild?: boolean }>(
({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "div";
return (
<Comp
ref={ref}
data-sidebar="group-label"
className={cn(
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] 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}
/>
);
},
);
SidebarGroupLabel.displayName = "SidebarGroupLabel";
const SidebarGroupAction = React.forwardRef<HTMLButtonElement, React.ComponentProps<"button"> & { asChild?: boolean }>(
({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
ref={ref}
data-sidebar="group-action"
className={cn(
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
},
);
SidebarGroupAction.displayName = "SidebarGroupAction";
const SidebarGroupContent = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(
({ className, ...props }, ref) => (
<div ref={ref} data-sidebar="group-content" className={cn("w-full text-sm", className)} {...props} />
),
);
SidebarGroupContent.displayName = "SidebarGroupContent";
const SidebarMenu = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(({ className, ...props }, ref) => (
<ul ref={ref} data-sidebar="menu" className={cn("flex w-full min-w-0 flex-col gap-1", className)} {...props} />
));
SidebarMenu.displayName = "SidebarMenu";
const SidebarMenuItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ className, ...props }, ref) => (
<li ref={ref} data-sidebar="menu-item" className={cn("group/menu-item relative", className)} {...props} />
));
SidebarMenuItem.displayName = "SidebarMenuItem";
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none 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",
},
},
);
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>
>(({ asChild = false, isActive = false, variant = "default", size = "default", tooltip, className, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
ref={ref}
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>
);
});
SidebarMenuButton.displayName = "SidebarMenuButton";
const SidebarMenuAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean;
showOnHover?: boolean;
}
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
ref={ref}
data-sidebar="menu-action"
className={cn(
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md: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 &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
className,
)}
{...props}
/>
);
});
SidebarMenuAction.displayName = "SidebarMenuAction";
const SidebarMenuBadge = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(
({ className, ...props }, ref) => (
<div
ref={ref}
data-sidebar="menu-badge"
className={cn(
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
"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}
/>
),
);
SidebarMenuBadge.displayName = "SidebarMenuBadge";
const SidebarMenuSkeleton = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
showIcon?: boolean;
}
>(({ className, showIcon = false, ...props }, ref) => {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`;
}, []);
return (
<div
ref={ref}
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>
);
});
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton";
const SidebarMenuSub = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(
({ className, ...props }, ref) => (
<ul
ref={ref}
data-sidebar="menu-sub"
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
),
);
SidebarMenuSub.displayName = "SidebarMenuSub";
const SidebarMenuSubItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ ...props }, ref) => (
<li ref={ref} {...props} />
));
SidebarMenuSubItem.displayName = "SidebarMenuSubItem";
const SidebarMenuSubButton = React.forwardRef<
HTMLAnchorElement,
React.ComponentProps<"a"> & {
asChild?: boolean;
size?: "sm" | "md";
isActive?: boolean;
}
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a";
return (
<Comp
ref={ref}
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 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 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
"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}
/>
);
});
SidebarMenuSubButton.displayName = "SidebarMenuSubButton";
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,7 @@
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} />;
}
export { Skeleton };

View File

@@ -0,0 +1,23 @@
import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import { cn } from "@/lib/utils";
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn("relative flex w-full touch-none select-none items-center", className)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
));
Slider.displayName = SliderPrimitive.Root.displayName;
export { Slider };

View File

@@ -0,0 +1,28 @@
/* eslint-disable react-refresh/only-export-components */
import { useTheme } from "next-themes";
import { Toaster as Sonner, toast } from "sonner";
type ToasterProps = React.ComponentProps<typeof Sonner>;
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
);
};
export { Toaster, toast };

View File

@@ -0,0 +1,27 @@
import * as React from "react";
import * as SwitchPrimitives from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",
)}
/>
</SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };

View File

@@ -0,0 +1,72 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
),
);
Table.displayName = "Table";
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />,
);
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
),
);
TableBody.displayName = "TableBody";
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tfoot ref={ref} className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)} {...props} />
),
);
TableFooter.displayName = "TableFooter";
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50", className)}
{...props}
/>
),
);
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className,
)}
{...props}
/>
),
);
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<td ref={ref} className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)} {...props} />
),
);
TableCell.displayName = "TableCell";
const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
({ className, ...props }, ref) => (
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
),
);
TableCaption.displayName = "TableCaption";
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };

View File

@@ -0,0 +1,58 @@
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "@/lib/utils";
const Tabs = TabsPrimitive.Root;
type TabsListProps = React.ComponentPropsWithoutRef<typeof TabsPrimitive.List> & {
orientation?: "horizontal" | "vertical";
};
const TabsList = React.forwardRef<React.ElementRef<typeof TabsPrimitive.List>, TabsListProps>(
({ className, orientation = "horizontal", ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
orientation === "vertical"
? "flex h-auto w-full flex-col gap-2 rounded-lg bg-muted p-2 text-muted-foreground"
: "inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className,
)}
{...props}
/>
),
);
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
className,
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className,
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "@/lib/utils";
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
{...props}
/>
);
});
Textarea.displayName = "Textarea";
export { Textarea };

View File

@@ -0,0 +1,112 @@
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-4 overflow-hidden rounded-md border p-6 pr-8 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",
success: "border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-50",
},
},
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 ring-offset-background transition-colors group-[.destructive]:border-muted/40 hover:bg-secondary group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 group-[.destructive]:focus:ring-destructive disabled:pointer-events-none disabled:opacity-50",
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-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 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", 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,24 @@
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,49 @@
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",
});
const ToggleGroup = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> & VariantProps<typeof toggleVariants>
>(({ className, variant, size, children, ...props }, ref) => (
<ToggleGroupPrimitive.Root ref={ref} className={cn("flex items-center justify-center gap-1", className)} {...props}>
<ToggleGroupContext.Provider value={{ variant, size }}>{children}</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
));
ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName;
const ToggleGroupItem = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> & VariantProps<typeof toggleVariants>
>(({ className, children, variant, size, ...props }, ref) => {
const context = React.useContext(ToggleGroupContext);
return (
<ToggleGroupPrimitive.Item
ref={ref}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
className,
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
);
});
ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;
export { ToggleGroup, ToggleGroupItem };

View File

@@ -0,0 +1,38 @@
/* eslint-disable react-refresh/only-export-components */
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 rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline: "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>
>(({ className, variant, size, ...props }, ref) => (
<TogglePrimitive.Root ref={ref} className={cn(toggleVariants({ variant, size, className }))} {...props} />
));
Toggle.displayName = TogglePrimitive.Root.displayName;
export { Toggle, toggleVariants };

View File

@@ -0,0 +1,28 @@
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md 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",
className,
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };

View File

@@ -0,0 +1,3 @@
import { useToast, toast } from "@/hooks/use-toast";
export { useToast, toast };

View File

@@ -0,0 +1,74 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { api } from '@/lib/api';
import type { UserProfileSchema } from '@/lib/types';
type User = UserProfileSchema;
interface AuthContextType {
user: User | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
checkAuth();
}, []);
const checkAuth = async () => {
const token = localStorage.getItem('access_token');
if (token) {
try {
const profile = await api.getProfile();
setUser(profile as User);
} catch (error) {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
}
}
setLoading(false);
};
const login = async (email: string, password: string) => {
const response = await api.login({ email, password });
localStorage.setItem('access_token', response.access_token);
localStorage.setItem('refresh_token', response.refresh_token);
await checkAuth();
};
const logout = () => {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
setUser(null);
};
return (
<AuthContext.Provider
value={{
user,
loading,
login,
logout,
isAuthenticated: !!user,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}

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

View File

@@ -0,0 +1,186 @@
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 };

109
frontend/src/index.css Normal file
View File

@@ -0,0 +1,109 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
* {
font-family: 'Vazirmatn', sans-serif;
}
/* Definition of the design system. All colors, gradients, fonts, etc should be defined here.
All colors MUST be HSL.
*/
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.5rem;
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary: 240 5.9% 10%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
--sidebar-background: 240 5.9% 10%;
--sidebar-foreground: 240 4.8% 95.9%;
--sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-border: 240 3.7% 15.9%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

661
frontend/src/lib/api.ts Normal file
View File

@@ -0,0 +1,661 @@
import type * as Types from './types';
const API_BASE_URL = 'https://api.east-guilan-ce.ir';
type ApiErrorBody = {
error?: string;
detail?: string;
message?: string;
};
class ApiClient {
private baseUrl: string;
private isRefreshing = false;
private refreshSubscribers: Array<(token: string) => void> = [];
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
private getAuthHeaders(): HeadersInit {
const token = localStorage.getItem('access_token');
return {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
}
private async refreshAccessToken(): Promise<string> {
const refreshToken = localStorage.getItem('refresh_token');
if (!refreshToken) {
throw new Error('No refresh token available');
}
const response = await fetch(`${this.baseUrl}/api/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!response.ok) {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
throw new Error('Session expired. Please login again.');
}
const data: Types.TokenSchema = await response.json();
localStorage.setItem('access_token', data.access_token);
localStorage.setItem('refresh_token', data.refresh_token);
return data.access_token;
}
private onRefreshed(token: string) {
this.refreshSubscribers.forEach(callback => callback(token));
this.refreshSubscribers = [];
}
private addRefreshSubscriber(callback: (token: string) => void) {
this.refreshSubscribers.push(callback);
}
async request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const url = `${this.baseUrl}${endpoint}`;
const config: RequestInit = {
...options,
headers: {
...this.getAuthHeaders(),
...options.headers,
},
};
const response = await fetch(url, config);
// Handle 401 with automatic token refresh
if (response.status === 401 && localStorage.getItem('refresh_token')) {
if (!this.isRefreshing) {
this.isRefreshing = true;
try {
const newToken = await this.refreshAccessToken();
this.isRefreshing = false;
this.onRefreshed(newToken);
// After you obtained `newToken` successfully:
const retryConfig: RequestInit = {
...options,
headers: {
...(options.headers || {}),
Authorization: `Bearer ${newToken}`, // put last so it can't be overwritten
},
};
const retryResponse = await fetch(url, retryConfig);
if (!retryResponse.ok) {
const err = await retryResponse.json().catch(() => ({}));
throw new Error(err.error || err.detail || 'Request failed');
}
return retryResponse.json();
} catch (error) {
this.isRefreshing = false;
throw error;
}
} else {
return new Promise((resolve, reject) => {
this.addRefreshSubscriber(async (token: string) => {
try {
const retryConfig: RequestInit = {
...options,
headers: {
...(options.headers || {}),
Authorization: `Bearer ${token}`,
},
};
const retryResponse = await fetch(url, retryConfig);
if (!retryResponse.ok) {
const err = (await retryResponse.json().catch(() => ({}))) as ApiErrorBody;
reject(new Error(err.error || err.detail || 'Request failed after refresh'));
} else {
resolve(retryResponse.json());
}
} catch (e) {
reject(e);
}
});
});
}
}
if (!response.ok) {
const body = (await response.json().catch(() => ({}))) as ApiErrorBody;
const message =
body?.error || body?.detail || body?.message || 'خطای ناشناخته رخ داد';
throw new Error(message);
}
return response.json() as Promise<T>;
}
// ============= Auth Endpoints =============
async register(data: Types.UserRegistrationSchema) {
return this.request<Types.MessageSchema>('/api/auth/register', {
method: 'POST',
body: JSON.stringify(data),
});
}
async login(data: Types.UserLoginSchema) {
return this.request<Types.TokenSchema>('/api/auth/login', {
method: 'POST',
body: JSON.stringify(data),
});
}
async refreshToken(data: Types.TokenRefreshIn) {
return this.request<Types.TokenSchema>('/api/auth/refresh', {
method: 'POST',
body: JSON.stringify(data),
});
}
async verifyEmail(token: string): Promise<Types.MessageSchema> {
const url = `${this.baseUrl}/api/auth/verify-email/${encodeURIComponent(token)}`;
const response = await fetch(url, { method: 'GET' });
if (response.ok) {
return response.json() as Promise<Types.MessageSchema>;
}
const data = (await response.json().catch(() => ({}))) as ApiErrorBody;
const errMsg: string =
(data && (data.error || data.detail)) || 'خطای ناشناخته رخ داد';
throw new Error(errMsg);
}
async resendVerification(email: string) {
return this.request<Types.MessageSchema>(
`/api/auth/resend-verification?email=${encodeURIComponent(email)}`,
{ method: 'POST' }
);
}
async getProfile() {
const token = localStorage.getItem('access_token');
return this.request<Types.UserProfileSchema>('/api/auth/profile'
);
}
async updateProfile(data: Types.UserUpdateSchema) {
return this.request<Types.UserProfileSchema>('/api/auth/profile', {
method: 'PUT',
body: JSON.stringify(data),
});
}
async uploadProfilePicture(file: File) {
const formData = new FormData();
formData.append('file', file);
const token = localStorage.getItem('access_token');
const response = await fetch(`${this.baseUrl}/api/auth/profile/picture`, {
method: 'POST',
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: formData,
});
if (!response.ok) {
const error: Types.ErrorSchema = await response.json().catch(() => ({
detail: 'خطای آپلود تصویر',
}));
throw new Error(error.detail);
}
return response.json() as Promise<Types.MessageSchema>;
}
async deleteProfilePicture() {
return this.request<Types.MessageSchema>('/api/auth/profile/picture', {
method: 'DELETE',
});
}
async requestPasswordReset(email: string) {
return this.request<Types.MessageSchema>('/api/auth/request-password-reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
}
async resetPasswordConfirm(token: string, new_password: string) {
return this.request<Types.MessageSchema>('/api/auth/reset-password-confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, new_password }),
});
}
async checkUsername(username: string) {
return this.request<Types.UsernameCheckSchema>(
`/api/auth/check-username?username=${encodeURIComponent(username)}`
);
}
// Admin auth endpoints
async listDeletedUsers() {
return this.request<Types.UserProfileSchema[]>('/api/auth/users/deleted');
}
async restoreUser(userId: number) {
return this.request<Types.MessageSchema>(`/api/auth/users/${userId}/restore`, {
method: 'POST',
});
}
async listUsers(params?: {
search?: string;
role?: 'staff' | 'superuser';
student_id?: string;
university?: string;
major?: string;
is_active?: 'true' | 'false';
limit?: number;
offset?: number;
}) {
const query = new URLSearchParams();
if (params?.search) query.set('search', params.search);
if (params?.role) query.set('role', params.role);
if (params?.student_id) query.set('student_id', params.student_id);
if (params?.university) query.set('university', params.university);
if (params?.major) query.set('major', params.major);
if (params?.is_active) query.set('is_active', params.is_active);
if (params?.limit != null) query.set('limit', String(params.limit));
if (params?.offset != null) query.set('offset', String(params.offset));
return this.request<Types.UserListSchema[]>(`/api/auth/users${query.toString() ? `?${query.toString()}` : ''}`);
}
// ============= Blog Endpoints =============
async getPosts(params?: {
page?: number;
limit?: number;
category?: string;
tag?: string;
search?: string;
featured?: boolean;
author?: string;
}) {
const queryParams = new URLSearchParams();
if (params?.page) queryParams.append('page', params.page.toString());
if (params?.limit) queryParams.append('limit', params.limit.toString());
if (params?.category) queryParams.append('category', params.category);
if (params?.tag) queryParams.append('tag', params.tag);
if (params?.search) queryParams.append('search', params.search);
if (params?.featured !== undefined) queryParams.append('featured', params.featured.toString());
if (params?.author) queryParams.append('author', params.author);
const query = queryParams.toString();
return this.request<Types.PostListSchema[]>(`/api/blog/posts${query ? `?${query}` : ''}`);
}
async getPost(slug: string) {
return this.request<Types.PostDetailSchema>(`/api/blog/posts/${slug}`);
}
async createPost(data: Types.PostCreateSchema) {
return this.request<Types.PostDetailSchema>('/api/blog/posts', {
method: 'POST',
body: JSON.stringify(data),
});
}
async updatePost(slug: string, data: Types.PostCreateSchema) {
return this.request<Types.PostDetailSchema>(`/api/blog/posts/${slug}`, {
method: 'PUT',
body: JSON.stringify(data),
});
}
async deletePost(slug: string) {
return this.request<Types.MessageSchema>(`/api/blog/posts/${slug}`, {
method: 'DELETE',
});
}
async listDeletedPosts() {
return this.request<Types.PostListSchema[]>('/api/blog/deleted/posts');
}
async restorePost(postId: number) {
return this.request<Types.MessageSchema>(`/api/blog/deleted/posts/${postId}/restore`, {
method: 'POST',
});
}
// Comments
async getComments(slug: string) {
return this.request<Types.CommentSchema[]>(`/api/blog/posts/${slug}/comments`);
}
async createComment(slug: string, data: Types.CommentCreateSchema) {
return this.request<Types.CommentSchema>(`/api/blog/posts/${slug}/comments`, {
method: 'POST',
body: JSON.stringify(data),
});
}
async listDeletedComments() {
return this.request<Types.CommentSchema[]>('/api/blog/deleted/comments');
}
async restoreComment(commentId: number) {
return this.request<Types.MessageSchema>(`/api/blog/deleted/comments/${commentId}/restore`, {
method: 'POST',
});
}
// Likes
async toggleLike(slug: string) {
return this.request<Types.MessageSchema>(`/api/blog/posts/${slug}/like`, {
method: 'POST',
});
}
async getLikesCount(slug: string) {
return this.request<Types.MessageSchema>(`/api/blog/posts/${slug}/likes`);
}
// Categories
async getCategories() {
return this.request<Types.CategorySchema[]>('/api/blog/categories');
}
async getCategory(slug: string) {
return this.request<Types.CategorySchema>(`/api/blog/categories/${slug}`);
}
async listDeletedCategories() {
return this.request<Types.CategorySchema[]>('/api/blog/deleted/categories');
}
async restoreCategory(categoryId: number) {
return this.request<Types.MessageSchema>(`/api/blog/deleted/categories/${categoryId}/restore`, {
method: 'POST',
});
}
// Tags
async getTags() {
return this.request<Types.TagSchema[]>('/api/blog/tags');
}
async getTag(slug: string) {
return this.request<Types.TagSchema>(`/api/blog/tags/${slug}`);
}
async listDeletedTags() {
return this.request<Types.TagSchema[]>('/api/blog/deleted/tags');
}
async restoreTag(tagId: number) {
return this.request<Types.MessageSchema>(`/api/blog/deleted/tags/${tagId}/restore`, {
method: 'POST',
});
}
// ============= Events Endpoints =============
async getEvents(params: {
status?: 'draft' | 'published' | 'cancelled' | 'completed';
statuses?: Array<'draft' | 'published' | 'cancelled' | 'completed'>; // جدید: چندتا وضعیت
event_type?: 'online' | 'on_site' | 'hybrid';
search?: string;
limit?: number;
offset?: number;
} = {}) {
const q = new URLSearchParams();
if (params.statuses?.length) {
params.statuses.forEach(s => q.append('status', s));
} else if (params.status) {
q.set('status', params.status);
}
if (params.event_type) q.set('event_type', params.event_type);
if (params.search) q.set('search', params.search);
if (params.limit != null) q.set('limit', String(params.limit));
if (params.offset != null) q.set('offset', String(params.offset));
const url = `/api/events/${q.toString() ? `?${q.toString()}` : ''}`;
return this.request<Types.EventListItemSchema[]>(url, { method: 'GET' });
}
async getEventBySlug(slug: string) {
return this.request<Types.EventDetailSchema>(`/api/events/slug/${encodeURIComponent(slug)}`, { method: 'GET' });
}
async getEventAdminDetail(eventId: number) {
return this.request<Types.EventAdminDetailSchema>(`/api/events/${eventId}/admin-detail`);
}
async listEventRegistrationsAdmin(
eventId: number,
params?: {
statuses?: string[];
university?: string;
major?: string;
search?: string;
limit?: number;
offset?: number;
}
) {
const query = new URLSearchParams();
if (params?.statuses?.length) {
params.statuses.forEach((status) => query.append('status', status));
}
if (params?.university) query.set('university', params.university);
if (params?.major) query.set('major', params.major);
if (params?.search) query.set('search', params.search);
if (params?.limit != null) query.set('limit', String(params.limit));
if (params?.offset != null) query.set('offset', String(params.offset));
return this.request<Types.PaginatedResponse<Types.RegistrationAdminSchema>>(
`/api/events/${eventId}/admin-registrations${query.toString() ? `?${query.toString()}` : ''}`
);
}
async updateEvent(eventId: number, data: Types.EventUpdateSchema) {
return this.request<Types.EventSchema>(`/api/events/${eventId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
}
async deleteEvent(eventId: number) {
return this.request<Types.MessageSchema>(`/api/events/${eventId}`, {
method: 'DELETE',
});
}
async registerForEvent(eventId: number, discountCode?: string | null) {
const payload = (discountCode ?? '').trim();
const init: RequestInit = { method: 'POST' };
if (payload) {
init.headers = { 'Content-Type': 'application/json' };
init.body = JSON.stringify({ discount_code: payload });
}
return this.request<Types.EventRegistrationSchema>(`/api/events/${eventId}/register`, init);
}
async ChangeRegistrationStatus(registrationId: number, status: string) {
return this.request(
`/api/events/registrations/${registrationId}`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: status }),
}
);
}
async listEventRegistrations(eventId: number, limit = 20, offset = 0) {
const url = `/api/events/${eventId}/registrations?limit=${limit}&offset=${offset}`;
return this.request<Types.EventRegistrationSchema[]>(url, { method: 'GET' });
}
async cancelEventRegistration(eventId: number) {
return this.request<Types.MessageSchema>(`/api/events/${eventId}/register`, {
method: 'DELETE',
});
}
async verifyMyRegistration(ticket_id: string) {
return this.request<{
event_image: string;
event_title: string;
event_type: string;
ticket_id: string;
status: string;
registered_at: string;
success_markdown: string;
}>(`/api/events/registerations/verify/${ticket_id}`, {method: 'GET'});
}
async getMyRegistrations() {
return this.request<Types.MyEventRegistrationSchema[]>(
`/api/events/my-registrations`,
{ method: 'GET' }
);
}
async getRegistrationStatus(eventId: number) {
return this.request<Types.RegistrationStatusSchema>(
`/api/events/${eventId}/is-registered`,
{ method: 'GET' }
);
}
// ============= Payment Endpoints =============
async createPayment(input: {
event_id: number;
description: string;
discount_code?: string | null;
mobile?: string | null;
email?: string | null;
}) {
return this.request<Types.CreatePaymentOut>(
'/api/payments/create',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
}
);
}
async getPaymentByRef(refId: string) {
return this.request<{
ref_id: string;
authority: string;
base_amount: number;
discount_amount: number;
amount: number;
status: 'INIT' | 'PENDING' | 'PAID' | 'FAILED' | 'CANCELED';
verified_at?: string | null;
event: {
id: number;
title: string;
slug: string;
image_url?: string | null;
success_markdown?: string | null;
};
}>(`/api/payments/by-ref/${encodeURIComponent(refId)}`, { method: 'GET' });
}
async checkDiscountCode(event_id: number, code: string) {
return this.request<{
discount_amount: number;
final_price: number;
}>(
`/api/payments/coupon/check`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({code: code, event_id: event_id}),
}
);
}
// ============= Gallery Endpoints =============
async getGalleryImages(params?: {
page?: number;
limit?: number;
tag?: string;
}) {
const queryParams = new URLSearchParams();
if (params?.page) queryParams.append('page', params.page.toString());
if (params?.limit) queryParams.append('limit', params.limit.toString());
if (params?.tag) queryParams.append('tag', params.tag);
const query = queryParams.toString();
return this.request<Types.GalleryImageSchema[]>(`/api/gallery/images${query ? `?${query}` : ''}`);
}
async uploadGalleryImage(file: File, data: Types.GalleryImageCreateSchema) {
const formData = new FormData();
formData.append('file', file);
formData.append('title', data.title);
if (data.description) formData.append('description', data.description);
if (data.tag_ids) formData.append('tag_ids', JSON.stringify(data.tag_ids));
const token = localStorage.getItem('access_token');
const response = await fetch(`${this.baseUrl}/api/gallery/images`, {
method: 'POST',
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: formData,
});
if (!response.ok) {
const error: Types.ErrorSchema = await response.json().catch(() => ({
detail: 'خطای آپلود تصویر',
}));
throw new Error(error.detail);
}
return response.json() as Promise<Types.GalleryImageSchema>;
}
async deleteGalleryImage(imageId: number) {
return this.request<Types.MessageSchema>(`/api/gallery/images/${imageId}`, {
method: 'DELETE',
});
}
async getMajors(): Promise<Types.MajorOption[]> {
return this.request('/api/meta/majors', { method: 'GET' });
}
async getUniversities(): Promise<Types.MajorOption[]> {
return this.request('/api/meta/universities', { method: 'GET' });
}
async subscribeNewsletter(email: string) {
return this.request<{ message: string, success: boolean }>(
`/api/communications/newsletter/subscribe/`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: email }),
}
);
}
}
export const api = new ApiClient(API_BASE_URL);

File diff suppressed because one or more lines are too long

354
frontend/src/lib/types.ts Normal file
View File

@@ -0,0 +1,354 @@
// API Response Types based on Swagger schema
export interface MessageSchema {
message: string;
}
export interface ErrorSchema {
detail: string;
}
// Auth Types
export interface TokenSchema {
access_token: string;
refresh_token: string;
}
export interface MajorOption {
code: string;
label: string;
}
export interface UserProfileSchema {
id: number;
email: string;
username: string;
first_name: string;
last_name: string;
profile_picture?: string;
bio?: string;
student_id?: string | null;
year_of_study?: number;
university?: string;
major?: string;
date_joined: string;
is_email_verified?: boolean;
is_active?: boolean;
is_staff?: boolean;
is_superuser?: boolean;
is_committee?: boolean;
is_deleted?: boolean;
deleted_at?: string | null;
}
export interface UserListSchema {
id: number;
username: string;
email: string;
first_name: string;
last_name: string;
full_name?: string | null;
is_active: boolean;
is_staff: boolean;
is_superuser: boolean;
date_joined: string;
}
export interface UserRegistrationSchema {
email: string;
password: string;
username: string;
first_name: string;
last_name: string;
student_id: string;
year_of_study: number;
major: string;
university: string;
}
export type UserUpdateSchema = {
first_name?: string | null;
last_name?: string | null;
bio?: string | null;
year_of_study?: number | null;
major?: string | null;
university?: string | null;
student_id?: number | null;
};
export interface UserLoginSchema {
email: string;
password: string;
}
export interface TokenRefreshIn {
refresh_token: string;
}
export interface UsernameCheckSchema {
available: boolean;
}
export interface PasswordResetRequestSchema {
email: string;
}
export interface PasswordResetConfirmSchema {
token: string;
password: string;
}
// Blog Types
export interface PostListSchema {
id: number;
title: string;
slug: string;
excerpt?: string;
featured_image?: string;
author: {
id: number;
username: string;
first_name: string;
last_name: string;
profile_picture?: string;
};
category?: {
id: number;
name: string;
slug: string;
description?: string;
};
tags: Array<{
id: number;
name: string;
slug: string;
}>;
status: string;
published_at?: string;
created_at: string;
is_featured: boolean;
reading_time?: number;
}
export interface PostDetailSchema extends PostListSchema {
content: string;
updated_at: string;
views_count?: number;
}
export interface PostCreateSchema {
title: string;
content: string;
summary: string;
category_id?: number;
tag_ids?: number[];
featured_image?: string;
is_featured?: boolean;
status?: 'draft' | 'published';
}
export interface CommentSchema {
id: number;
content: string;
author: {
id: number;
username: string;
first_name: string;
last_name: string;
};
post_id: number;
post_title: string;
post_slug: string;
parent_id?: number;
created_at: string;
is_approved: boolean;
}
export interface CommentCreateSchema {
content: string;
parent_id?: number;
}
export interface CategorySchema {
id: number;
name: string;
slug: string;
description?: string;
created_at: string;
}
export interface TagSchema {
id: number;
name: string;
slug: string;
created_at: string;
}
// Events Types
export interface EventListItemSchema {
id: number;
title: string;
slug: string;
description: string;
featured_image?: string | null;
absolute_featured_image_url?: string | null;
event_type: 'online' | 'on_site' | 'hybrid';
address?: string | null;
location?: string | null;
online_link?: string | null;
start_time: string; // ISO
end_time: string; // ISO
registration_start_date?: string | null;
registration_end_date?: string | null;
capacity?: number | null;
price?: number | null;
status: 'draft' | 'published' | 'cancelled' | 'completed';
registration_count: number;
created_at: string;
}
export interface EventGalleryItem {
id: number;
title: string;
description: string;
absolute_image_url?: string | null;
width?: number;
height?: number;
}
export interface EventDetailSchema extends EventListItemSchema {
description_html: string;
gallery_images: EventGalleryItem[];
updated_at: string;
registration_success_markdown: string;
}
export interface EventCreateSchema {
title: string;
description: string;
start_date: string;
end_date?: string;
location: string;
capacity?: number;
event_image?: string;
requirements?: string;
is_registration_open?: boolean;
}
export interface PaymentAdminSchema {
id: number;
authority?: string | null;
ref_id?: string | null;
status: number;
status_label: string;
base_amount: number;
discount_amount: number;
amount: number;
verified_at?: string | null;
created_at: string;
discount_code?: string | null;
}
export interface RegistrationAdminSchema {
id: number;
ticket_id: string;
status: 'pending' | 'confirmed' | 'cancelled' | 'attended';
status_label: string;
registered_at: string;
final_price?: number | null;
discount_amount?: number | null;
user: {
id: number;
username: string;
first_name: string;
last_name: string;
email: string;
};
payments: PaymentAdminSchema[];
}
export interface EventAdminDetailSchema extends EventDetailSchema {
registrations: RegistrationAdminSchema[];
}
export interface EventUpdateSchema {
title?: string;
description?: string;
event_type?: 'online' | 'on_site' | 'hybrid';
address?: string | null;
location?: string | null;
online_link?: string | null;
start_time?: string;
end_time?: string | null;
registration_start_date?: string | null;
registration_end_date?: string | null;
capacity?: number | null;
price?: number | null;
status?: 'draft' | 'published' | 'cancelled' | 'completed';
gallery_image_ids?: number[] | null;
}
export interface EventRegistrationSchema {
id: number;
status: 'pending' | 'confirmed' | 'cancelled' | 'attended';
ticket_id: string;
registered_at: string;
created_at: string;
updated_at: string;
user: {
id: number;
username: string;
first_name: string;
last_name: string;
};
event_id: number;
}
export interface RegistrationStatusSchema {
is_registered: boolean;
}
export interface MyEventRegistrationSchema {
id: number;
created_at: string;
status: 'pending' | 'confirmed' | 'cancelled' | 'attended';
event: EventListItemSchema;
}
// Gallery Types
export interface GalleryImageSchema {
id: number;
title: string;
description?: string;
image: string;
uploaded_by: {
id: number;
username: string;
};
created_at: string;
tags: TagSchema[];
}
export interface GalleryImageCreateSchema {
title: string;
description?: string;
tag_ids?: number[];
}
// Pagination
export interface PaginatedResponse<T> {
results: T[];
count: number;
next?: string;
previous?: string;
}
// payment
export interface CreatePaymentOut {
start_pay_url: string;
authority: string;
base_amount: number;
discount_amount: number;
amount: number;
}

99
frontend/src/lib/utils.ts Normal file
View File

@@ -0,0 +1,99 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import type * as Types from '@/lib/types';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatJalali(iso?: string, withTime: boolean = true): string {
if (!iso) return '—';
try {
const d = new Date(iso);
// آیا تقویم Persian در محیط کاربر پشتیبانی می‌شود؟
const hasPersian = Intl.DateTimeFormat.supportedLocalesOf(['fa-IR-u-ca-persian']).length > 0;
const locale = hasPersian ? 'fa-IR-u-ca-persian' : 'fa-IR';
const weekday = new Intl.DateTimeFormat(locale, { weekday: 'long' }).format(d);
const day = new Intl.DateTimeFormat(locale, { day: 'numeric' }).format(d);
const month = new Intl.DateTimeFormat(locale, { month: 'long' }).format(d);
const year = new Intl.DateTimeFormat(locale, { year: 'numeric' }).format(d);
const datePart = `${weekday}، ${day} ${month} ${year}`;
if (!withTime) return datePart;
const timePart = new Intl.DateTimeFormat('fa-IR', {
hour: '2-digit',
minute: '2-digit',
// اگر 24ساعته می‌خوای: hourCycle: 'h23'
}).format(d);
return `${datePart}, ساعت ${timePart}`;
} catch {
return '—';
}
}
const DEFAULT_THUMB = '/images/event-placeholder.svg';
export const getThumbUrl = (e: Types.EventListItemSchema) =>
e.absolute_featured_image_url ||
e.featured_image ||
DEFAULT_THUMB;
const PERSIAN_DIGITS = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
export function toPersianDigits(value?: string | number | null) {
if (value == null) return '—';
return String(value).replace(/\d/g, (digit) => PERSIAN_DIGITS[Number(digit)] ?? digit);
}
export function formatNumberPersian(value?: number | string | null) {
if (value == null) return '—';
const num = Number(value);
if (!Number.isFinite(num)) return '—';
return toPersianDigits(num.toLocaleString('en-US'));
}
export function formatToman(value?: number | null) {
if (value == null) return '—';
const amount = Math.floor(Number(value) / 10);
if (!Number.isFinite(amount)) return '—';
return `${toPersianDigits(amount.toLocaleString('en-US'))} تومان`;
}
type ApiErrorLike = {
error?: string;
detail?: string;
message?: string;
};
const resolveMessageFromRecord = (record?: ApiErrorLike) => {
if (!record) return undefined;
return record.error || record.detail || record.message;
};
export function resolveErrorMessage(error: unknown, fallback = 'خطایی رخ داد. لطفاً دوباره تلاش کنید.') {
if (error instanceof Error && error.message) {
return error.message;
}
if (typeof error === 'string' && error.trim()) {
return error;
}
if (typeof error === 'object' && error !== null) {
const err = error as {
response?: { data?: ApiErrorLike };
data?: ApiErrorLike;
error?: string;
detail?: string;
message?: string;
};
return (
resolveMessageFromRecord(err.response?.data) ||
resolveMessageFromRecord(err.data) ||
resolveMessageFromRecord(err) ||
fallback
);
}
return fallback;
}

11
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,11 @@
// import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { ThemeProvider } from '@/components/ThemeProvider';
createRoot(document.getElementById("root")!).render(
<ThemeProvider defaultTheme="system" storageKey="egce-theme">
<App />
</ThemeProvider>
);

View File

@@ -0,0 +1,384 @@
import React from 'react';
import { Helmet } from 'react-helmet-async';
import { Link } from 'react-router-dom';
// ------ داده‌های قابل تنظیم ------
const SITE_URL = 'https://east-guilan-ce.ir';
const SITE_NAME_FA = 'انجمن علمی کامپیوتر شرق گیلان';
const ABOUT_CANONICAL = `${SITE_URL}/about`;
const ABOUT_TITLE = `درباره ما | ${SITE_NAME_FA}`;
const ABOUT_DESCRIPTION =
'آشنایی با تاریخچه، مأموریت‌ها و دستاوردهای انجمن علمی کامپیوتر شرق گیلان و راه‌های مشارکت دانشجویان در برنامه‌های انجمن.';
const ABOUT_KEYWORDS =
'انجمن علمی کامپیوتر شرق گیلان, انجمن علمی مهندسی کامپیوتر دانشگاه گیلان، انجمن علمی علوم کامپیوتر، انجمن علمی شرق گیلان، انجمن علمی مهندسی کامپیوتر شرق گیلان، دانشکده فنی و مهندسی شرق گیلان، انجمن علمی کامپیوتر, فعالیت‌های دانشجویی, انجمن‌های علمی ایران, رویدادهای فناوری، برنامه نویسی، انجمن علمی دانشجویی، دانشگاه گیلان، فنی شرق';
const ABOUT_STRUCTURED_DATA = {
'@context': 'https://schema.org',
'@type': 'AboutPage',
name: ABOUT_TITLE,
description: ABOUT_DESCRIPTION,
url: ABOUT_CANONICAL,
mainEntity: {
'@type': 'Organization',
name: SITE_NAME_FA,
url: SITE_URL,
logo: `${SITE_URL}/favicon.ico`,
sameAs: [
'https://instagram.com/guilance.ir',
'https://t.me/guilance',
'https://t.me/guilancea'
],
areaServed: 'IR',
contactPoint: [
{
'@type': 'ContactPoint',
contactType: 'customer support',
email: 'eastguilanceassociation@gmail.com',
availableLanguage: ['fa'],
areaServed: 'IR'
}
]
}
};
const ORG = {
title: 'انجمن‌های علمی کامپیوتر گیلان', // تیتر کلی
subtitle:
'پیوند دانشگاه و صنعت با برگزاری رویدادها، کارگاه‌ها و نشست‌های تخصصی — با محوریت رشد مهارت‌های فنی و مسیرهای شغلی.',
foundedYear: '۱۴۰۴',
membersApprox: '۱۰۰+',
eventsCount: '۱۰+',
volunteersCount: '۲۰+',
};
// اگر چند انجمن زیرمجموعه دارید، اینجا معرفی کنید
const ASSOCIATIONS = [
{
name: 'انجمن علمی مهندسی کامپیوتر دانشکده‌ی فنی شرق',
university: 'دانشگاه گیلان',
city: 'رودسر',
foundedYear: '۱۳۹۲',
about:
'برگزاری رویدادهای آموزشی و صنعتی، منتورینگ دانشجویی، و اتصال دانشجویان به فرصت‌های شغلی و پژوهشی.',
focusAreas: ['مهندسی نرم‌افزار', 'هوش مصنوعی و داده', 'طراحی محصول', 'DevOps/امنیت'],
links: {
website: 'https://east-guilan-ce.ir',
instagram: '"https://instagram.com/guilance.ir',
telegram: 'https://t.me/guilance',
email: 'eastguilanceassociation@gmail.com',
},
},
{
name: 'انجمن علمی مهندسی کامپیوتر دانشکده‌ی فنی',
university: 'دانشگاه گیلان',
city: 'رشت',
foundedYear: '۱۳۵۳',
about: 'برگزاری رویدادهای آموزشی و صنعتی، منتورینگ دانشجویی، و اتصال دانشجویان به فرصت‌های شغلی و پژوهشی.',
focusAreas: ['مهندسی نرم‌افزار', 'هوش مصنوعی و داده', 'DevOps'],
links: {
instagram: 'https://instagram.com/ce.guilan',
telegram: 'https://t.me/CSAOEF',
email: 'cesa@guilan.ac.ir'
},
},
{
name: 'انجمن علمی علوم کامپیوتر دانشکده‌ی علوم‌پایه',
university: 'دانشگاه گیلان',
city: 'رشت',
foundedYear: '۱۳۵۳',
about: 'برگزاری رویدادهای آموزشی و صنعتی، منتورینگ دانشجویی، و اتصال دانشجویان به فرصت‌های شغلی و پژوهشی.',
focusAreas: ['امنیت', 'سیستم‌عامل', 'سخت‌افزار'],
links: {
instagram: 'https://instagram.com/csguilan',
telegram: 'https://t.me/guilanCS',
},
},
];
// کمیته‌ها/گروه‌های کاری
const COMMITTEES = [
{
title: 'کمیته آموزش',
desc: 'برنامه‌ریزی و اجرای دوره‌ها و کارگاه‌های مهارتی، هماهنگی با مدرسین و طراحی مسیرهای یادگیری.'
},
{
title: 'کمیته صنعت و اشتغال',
desc: 'تعامل با شرکت‌ها، دعوت از متخصصان صنعت، و شبکه‌سازی برای فرصت‌های کارآموزی و استخدام.'
},
{
title: 'کمیته محتوای دیجیتال',
desc: 'تولید محتوای آموزشی، خبرنامه، مدیریت شبکه‌های اجتماعی و پوشش رسانه‌ای رویدادها.'
},
];
// راه‌های ارتباطی اصلی صفحه
const CONTACTS = [
{
label: 'ایمیل',
value: 'eastguilanceassociation@gmail.com',
href: 'mailto:eastguilanceassociation@gmail.com',
},
{
label: 'تلگرام',
value: '@GuilanCEA',
href: 'https://t.me/guilancea',
},
{
label: 'اینستاگرام',
value: '@GuilanCE.ir',
href: 'https://instagram.com/guilance.ir',
},
{
label: 'وب‌سایت',
value: 'east-guilan-ce.ir',
href: 'https://east-guilan-ce.ir',
},
];
export default function AboutUs() {
return (
<>
<Helmet>
<title>{ABOUT_TITLE}</title>
<meta name="description" content={ABOUT_DESCRIPTION} />
<meta name="keywords" content={ABOUT_KEYWORDS} />
<meta name="robots" content="index, follow" />
<link rel="canonical" href={ABOUT_CANONICAL} />
<meta property="og:title" content={ABOUT_TITLE} />
<meta property="og:description" content={ABOUT_DESCRIPTION} />
<meta property="og:type" content="website" />
<meta property="og:url" content={ABOUT_CANONICAL} />
<meta property="og:site_name" content={SITE_NAME_FA} />
<meta property="og:image" content={`${SITE_URL}/favicon.ico`} />
<meta property="og:locale" content="fa_IR" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={ABOUT_TITLE} />
<meta name="twitter:description" content={ABOUT_DESCRIPTION} />
<meta name="twitter:image" content={`${SITE_URL}/favicon.ico`} />
<script type="application/ld+json">{JSON.stringify(ABOUT_STRUCTURED_DATA)}</script>
</Helmet>
<div className="min-h-screen bg-background" dir="rtl">
{/* Hero */}
<section className="bg-gradient-to-b from-muted/40 to-transparent">
<div className="container mx-auto max-w-6xl px-4 py-12">
<h1 className="text-3xl md:text-4xl font-extrabold tracking-tight text-foreground">{ORG.title}</h1>
<p className="mt-3 text-muted-foreground leading-7">{ORG.subtitle}</p>
{/* آمار کوتاه */}
<div className="mt-6 grid grid-cols-2 gap-4 md:grid-cols-4">
<Stat label="سال تأسیس" value={ORG.foundedYear} />
<Stat label="اعضا" value={ORG.membersApprox} />
<Stat label="رویدادها" value={ORG.eventsCount} />
<Stat label="داوطلبان" value={ORG.volunteersCount} />
</div>
</div>
</section>
{/* درباره ما */}
<section className="container mx-auto max-w-6xl px-4 py-10">
<div className="grid gap-6 md:grid-cols-3">
<div className="md:col-span-2">
<Card>
<CardHeader title="ماموریت ما" subtitle="چرا اینجا هستیم؟" />
<div className="p-6 pt-0 text-sm leading-7 text-muted-foreground">
<p>
توانمندسازی دانشجویان با مهارتهای موردنیاز صنعت، ایجاد شبکههای حرفهای و فراهمکردن مسیرهای یادگیری
پروژهمحور؛ از معرفی نقشها و مسیرهای شغلی تا تمرین مهارتهای نرم و فنی.
</p>
</div>
</Card>
<Card className="mt-6">
<CardHeader title="ارزش‌های ما" subtitle="چه چیزهایی برای‌مان مهم است؟" />
<ul className="p-6 pt-0 grid grid-cols-1 gap-3 text-sm text-muted-foreground md:grid-cols-2">
<li className="rounded-xl border p-3">یادگیری پیوسته و اشتراک دانش</li>
<li className="rounded-xl border p-3">کیفیت، شفافیت و مسئولیتپذیری</li>
<li className="rounded-xl border p-3">فرصت برابر برای مشارکت</li>
<li className="rounded-xl border p-3">ارتباط مؤثر با صنعت و جامعه</li>
</ul>
</Card>
</div>
{/* تماس سریع */}
<div>
<Card>
<CardHeader title="راه‌های ارتباطی" subtitle="با ما در ارتباط باشید" />
<div className="p-6 pt-0 space-y-3">
{CONTACTS.map((c) => (
<a
key={c.label}
href={c.href}
target={c.href?.startsWith('http') ? '_blank' : undefined}
rel={c.href?.startsWith('http') ? 'noopener noreferrer' : undefined}
className="flex items-center justify-between rounded-xl border p-3 transition-colors hover:bg-muted/50"
>
<span className="text-sm text-foreground">{c.label}</span>
<span className="text-xs text-muted-foreground ltr:ml-2 rtl:mr-2 truncate">{c.value}</span>
</a>
))}
</div>
</Card>
<Card className="mt-6">
<CardHeader title="ساعات پاسخ‌گویی" subtitle="پشتیبانی داوطلبانه" />
<div className="p-6 pt-0 text-sm text-muted-foreground">
<p>روزهای شنبه تا چهارشنبه، ساعت ۱۰ تا ۱۸</p>
<p className="mt-2">پاسخها توسط تیم داوطلبان انجام میشود.</p>
</div>
</Card>
</div>
</div>
</section>
{/* انجمن‌ها */}
<section className="bg-muted/20">
<div className="container mx-auto max-w-6xl px-4 py-10">
<h2 className="text-2xl font-bold text-foreground">انجمنها</h2>
<p className="mt-2 text-sm text-muted-foreground">اطلاعات انجمنهای زیرمجموعه/همکار</p>
<div className="mt-6 grid gap-6 md:grid-cols-2">
{ASSOCIATIONS.map((a) => (
<Card key={a.name}>
<div className="p-6">
<div className="flex items-baseline justify-between gap-4">
<div>
<h3 className="text-lg font-semibold text-foreground">{a.name}</h3>
<p className="text-xs text-muted-foreground mt-1">
{a.university}{a.city ? `${a.city}` : ''}{' '}
{a.foundedYear && `• تأسیس: ${a.foundedYear}`}
</p>
</div>
</div>
<p className="mt-3 text-sm leading-7 text-muted-foreground">{a.about}</p>
{a.focusAreas?.length ? (
<div className="mt-4 flex flex-wrap gap-2">
{a.focusAreas.map((f) => (
<span key={f} className="rounded-full border px-3 py-1 text-xs text-muted-foreground">
{f}
</span>
))}
</div>
) : null}
<div className="mt-4 grid grid-cols-2 gap-3 text-sm">
{a.links?.website && (
<a className="rounded-xl border p-3 hover:bg-muted/50" href={a.links.website} target="_blank" rel="noreferrer">وبسایت</a>
)}
{a.links?.instagram && (
<a className="rounded-xl border p-3 hover:bg-muted/50" href={a.links.instagram} target="_blank" rel="noreferrer">اینستاگرام</a>
)}
{a.links?.telegram && (
<a className="rounded-xl border p-3 hover:bg-muted/50" href={a.links.telegram} target="_blank" rel="noreferrer">تلگرام</a>
)}
{a.links?.email && (
<a className="rounded-xl border p-3 hover:bg-muted/50" href={`mailto:${a.links.email}`}>ایمیل</a>
)}
</div>
</div>
</Card>
))}
</div>
</div>
</section>
{/* کمیته‌ها */}
<section className="container mx-auto max-w-6xl px-4 py-10">
<h2 className="text-2xl font-bold text-foreground">کمیتهها و گروههای کاری</h2>
<div className="mt-6 grid gap-4 md:grid-cols-3">
{COMMITTEES.map((c) => (
<Card key={c.title}>
<div className="p-5">
<h3 className="text-base font-semibold text-foreground">{c.title}</h3>
<p className="mt-2 text-sm text-muted-foreground leading-7">{c.desc}</p>
</div>
</Card>
))}
</div>
</section>
{/* پرسش‌های متداول */}
<section className="bg-muted/20">
<div className="container mx-auto max-w-6xl px-4 py-10">
<h2 className="text-2xl font-bold text-foreground">پرسشهای متداول</h2>
<div className="mt-6 space-y-3">
<FAQ q="چطور در رویدادها شرکت کنم؟" a="برای ثبت‌نام در رویدادها ابتدا باید حساب‌کاربری با کددانشجویی خود ایجاد کنید و سپس از طریق صفحه‌ی ثبت‌نام در رویداد موردنظرتان شرکت کنید :)" />
<FAQ q="آیا امکان همکاری انجمن‌ها/شرکت‌ها هم وجود دارد؟" a="بله، ما همیشه آماده‌ی همکاری با سازمان‌ها و انجمن‌های مختلف دانشگاه‌ها جهت توانمندسازی دانشجویان با مهارت‌های موردنیاز صنعت و ایجاد شبکه‌های حرفه‌ای هستیم." />
<FAQ q="برای سخنرانی/منتورینگ به چه چیزهایی نیاز است؟" a="رزومه کوتاه، موضوع پیشنهادی و زمان‌های دسترس‌پذیرتان را ارسال کنید تا هماهنگ کنیم." />
</div>
</div>
</section>
{/* نقشه و آدرس اختیاری */}
<section className="container mx-auto max-w-6xl px-4 py-10">
<h2 className="text-2xl font-bold text-foreground">نشانی دانشکده</h2>
<div className="mt-4 grid gap-6 md:grid-cols-2">
<Card>
<div className="p-5 text-sm text-muted-foreground leading-7">
<p>آدرس: گیلان، رودسر، واجارگاه، دانشکدهی فنی و مهندسی شرق گیلان</p>
<p>کدپستی: ۴۴۹۱۸۹۸۵۶۶</p>
<p>تلفن: ۰۱۳-۴۲۶۸۸۴۴۷</p>
<p className="mt-3">برای هماهنگی حضوری از قبل پیام بدهید.</p>
</div>
</Card>
<div className="rounded-xl border overflow-hidden min-h-[280px] bg-muted/40 flex items-center justify-center text-sm text-muted-foreground">
<iframe
src="https://maps.google.com/maps?q=37.06285,50.42324&hl=fa&z=16&output=embed"
loading="lazy"
referrerPolicy="no-referrer-when-downgrade"
className="w-full aspect-video border-0"
/>
</div>
</div>
</section>
{/* CTA */}
<section className="bg-gradient-to-t from-muted/40 to-transparent">
<div className="container mx-auto max-w-6xl px-4 py-12 text-center">
<h3 className="text-xl md:text-2xl font-bold text-foreground">مایل به همکاری هستید؟</h3>
<p className="mt-2 text-sm text-muted-foreground">برای مشارکت داوطلبانه، سخنرانی، اسپانسری یا همکاری صنعتی به ما پیام دهید.</p>
<div className="mt-4 inline-flex gap-3">
<a href="mailto:eastguilanceassociation@gmail.com" className="rounded-xl border px-5 py-2 text-sm hover:bg-muted/50">ایجاد ارتباط</a>
<a href="https://t.me/guilancea" target="_blank" rel="noreferrer" className="rounded-xl bg-primary px-5 py-2 text-sm text-primary-foreground">
پیام در تلگرام
</a>
</div>
</div>
</section>
</div>
</>
);
}
// --------- اجزای کوچک ---------
function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="rounded-xl border bg-background p-4 text-center">
<div className="text-2xl font-extrabold text-foreground">{value}</div>
<div className="text-xs text-muted-foreground mt-1">{label}</div>
</div>
);
}
function Card({ children, className = '' }: React.PropsWithChildren<{ className?: string }>) {
return <div className={`rounded-2xl border bg-card text-card-foreground shadow-sm ${className}`}>{children}</div>;
}
function CardHeader({ title, subtitle }: { title: string; subtitle?: string }) {
return (
<div className="p-6 pb-4">
<h3 className="text-lg font-semibold text-foreground">{title}</h3>
{subtitle ? <p className="mt-1 text-xs text-muted-foreground">{subtitle}</p> : null}
</div>
);
}
function FAQ({ q, a }: { q: string; a: string }) {
return (
<details className="rounded-xl border bg-background p-4">
<summary className="cursor-pointer select-none text-sm font-medium text-foreground">{q}</summary>
<p className="mt-2 text-sm leading-7 text-muted-foreground">{a}</p>
</details>
);
}

View File

@@ -0,0 +1,214 @@
import * as React from 'react';
import { useParams, Link, Navigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/hooks/use-toast';
import { formatJalali, formatToman, resolveErrorMessage, toPersianDigits } from '@/lib/utils';
import { useAuth } from '@/contexts/AuthContext';
const registrationStatusOptions = [
{ value: 'confirmed', label: 'تایید شده' },
{ value: 'pending', label: 'در انتظار' },
{ value: 'cancelled', label: 'لغو شده' },
{ value: 'attended', label: 'حضور یافته' },
] as const;
const REGISTRATIONS_PAGE_SIZE = 10;
export default function AdminEventDetail() {
const { id } = useParams();
const { toast } = useToast();
const { user, isAuthenticated, loading } = useAuth();
const [statusFilter, setStatusFilter] = React.useState<typeof registrationStatusOptions[number]['value'] | 'all'>('all');
const [search, setSearch] = React.useState('');
const [regPage, setRegPage] = React.useState(1);
const eventId = Number(id);
const detailQuery = useQuery({
queryKey: ['admin', 'event-detail', eventId],
queryFn: () => api.getEventAdminDetail(eventId),
enabled: Number.isFinite(eventId),
});
const registrationsQuery = useQuery({
queryKey: ['admin', 'event', eventId, 'registrations', statusFilter, search, regPage],
enabled: Number.isFinite(eventId),
queryFn: () =>
api.listEventRegistrationsAdmin(eventId, {
statuses:
statusFilter === 'all'
? registrationStatusOptions.map((s) => s.value)
: [statusFilter],
search: search || undefined,
limit: REGISTRATIONS_PAGE_SIZE,
offset: (regPage - 1) * REGISTRATIONS_PAGE_SIZE,
}),
});
React.useEffect(() => {
if (detailQuery.error) {
toast({ title: 'خطا در دریافت جزئیات رویداد', description: resolveErrorMessage(detailQuery.error), variant: 'destructive' });
}
}, [detailQuery.error, toast]);
React.useEffect(() => {
if (registrationsQuery.error) {
toast({ title: 'خطا در ثبت‌نام‌ها', description: resolveErrorMessage(registrationsQuery.error), variant: 'destructive' });
}
}, [registrationsQuery.error, toast]);
if (loading) {
return <div className="min-h-screen flex items-center justify-center text-muted-foreground" dir="rtl">در حال بارگذاری...</div>;
}
if (!isAuthenticated || !(user?.is_staff || user?.is_superuser)) {
return <Navigate to="/" replace />;
}
if (!Number.isFinite(eventId)) {
return <div className="min-h-screen flex items-center justify-center" dir="rtl">شناسه رویداد معتبر نیست.</div>;
}
const event = detailQuery.data;
const paged = registrationsQuery.data;
const registrationPageCount = paged ? Math.max(1, Math.ceil(paged.count / REGISTRATIONS_PAGE_SIZE)) : 1;
return (
<div className="min-h-screen bg-background" dir="rtl">
<div className="container mx-auto px-4 py-6 space-y-6">
<div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
<div>
<h1 className="text-2xl font-bold">{event?.title ?? 'جزئیات رویداد'}</h1>
{event && (
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground mt-1">
<Badge variant="secondary">{event.status_label ?? event.status}</Badge>
{event.start_time ? <span>شروع: {formatJalali(event.start_time)}</span> : null}
{event.event_type ? <span>نوع: {event.event_type_label ?? event.event_type}</span> : null}
</div>
)}
</div>
<div className="flex flex-wrap gap-2">
<Button asChild>
<Link to={`/admin/events/${eventId}/edit`}>ویرایش پیشرفته</Link>
</Button>
<Button variant="outline" asChild>
<Link to="/admin/events">بازگشت</Link>
</Button>
</div>
</div>
{event && (
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardHeader>
<CardTitle>وضعیت</CardTitle>
<CardDescription>اطلاعات پایه رویداد</CardDescription>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<div>ظرفیت: {event.capacity ?? 'نامحدود'}</div>
<div>ثبتنامها: {toPersianDigits(event.registration_count ?? 0)}</div>
<div>قیمت: {formatToman(event.price)}</div>
</CardContent>
</Card>
<Card className="md:col-span-2">
<CardHeader>
<CardTitle>توضیحات</CardTitle>
</CardHeader>
<CardContent className="text-sm text-muted-foreground leading-6">
{event.description || 'توضیحی ثبت نشده است.'}
</CardContent>
</Card>
</div>
)}
<Card>
<CardHeader>
<CardTitle>ثبتنامها و پرداختها</CardTitle>
<CardDescription>لیست ثبتنامهای مرتبط با این رویداد</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
<div className="flex flex-wrap gap-2">
<Select value={statusFilter} onValueChange={(value) => { setStatusFilter(value as typeof statusFilter); setRegPage(1); }}>
<SelectTrigger className="w-full md:w-40">
<SelectValue placeholder="وضعیت">وضعیت: {statusFilter === 'all' ? 'همه' : statusFilter}</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">همه</SelectItem>
{registrationStatusOptions.map((s) => (
<SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Input
className="md:w-64"
placeholder="جستجو نام/ایمیل/نام‌کاربری"
value={search}
onChange={(e) => { setSearch(e.target.value); setRegPage(1); }}
/>
</div>
{registrationsQuery.isLoading ? (
<p className="text-sm text-muted-foreground">در حال بارگذاری ثبتنامها...</p>
) : !paged || paged.results.length === 0 ? (
<p className="text-sm text-muted-foreground">ثبتنامی یافت نشد.</p>
) : (
<ScrollArea className="rounded-md border max-h-[70vh]">
<div className="divide-y">
{paged.results.map((registration) => (
<div key={registration.id} className="p-4">
<div className="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
<div>
<div className="font-semibold">{registration.user.first_name} {registration.user.last_name}</div>
<div className="text-xs text-muted-foreground">{registration.user.email}</div>
</div>
<Badge variant={registration.status === 'confirmed' ? 'default' : 'outline'}>
{registration.status_label}
</Badge>
</div>
<div className="mt-2 grid gap-1 text-xs text-muted-foreground md:grid-cols-2 lg:grid-cols-3">
<div>نامکاربری: {registration.user.username}</div>
<div>کد بلیت: {registration.ticket_id}</div>
<div>تاریخ ثبتنام: {formatJalali(registration.registered_at)}</div>
<div>مبلغ پرداختی: {formatToman(registration.final_price ?? 0)}</div>
<div>تخفیف: {formatToman(registration.discount_amount ?? 0)}</div>
</div>
{registration.payments.length > 0 && (
<div className="mt-2 space-y-1 text-xs">
<div className="font-medium">پرداختها</div>
{registration.payments.map((payment) => (
<div key={payment.id} className="flex flex-wrap items-center justify-between gap-2 rounded border px-2 py-1">
<span className="text-muted-foreground">{payment.status_label}</span>
<span>{formatToman(payment.amount)}</span>
<span className="text-muted-foreground text-[11px]">Ref: {payment.ref_id ?? '—'}</span>
</div>
))}
</div>
)}
</div>
))}
</div>
</ScrollArea>
)}
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>صفحه {toPersianDigits(regPage)} از {toPersianDigits(registrationPageCount)}</span>
<div className="flex gap-2">
<Button size="sm" variant="outline" disabled={regPage <= 1} onClick={() => setRegPage((p) => Math.max(1, p - 1))}>
قبلی
</Button>
<Button size="sm" variant="outline" disabled={regPage >= registrationPageCount} onClick={() => setRegPage((p) => p + 1)}>
بعدی
</Button>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,270 @@
import * as React from 'react';
import { useNavigate, useParams, Navigate } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useAuth } from '@/contexts/AuthContext';
import { api } from '@/lib/api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { resolveErrorMessage } from '@/lib/utils';
const statusOptions = [
{ value: 'draft', label: 'پیش‌نویس' },
{ value: 'published', label: 'منتشر شده' },
{ value: 'cancelled', label: 'لغو شده' },
{ value: 'completed', label: 'برگزار شده' },
];
const typeOptions = [
{ value: 'online', label: 'آنلاین' },
{ value: 'on_site', label: 'حضوری' },
{ value: 'hybrid', label: 'ترکیبی' },
];
const toInputDateTime = (iso?: string | null) => {
if (!iso) return '';
const d = new Date(iso);
return `${d.getFullYear().toString().padStart(4, '0')}-${(d.getMonth() + 1)
.toString()
.padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}T${d
.getHours()
.toString()
.padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
};
export default function AdminEventEdit() {
const { user, isAuthenticated, loading } = useAuth();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const eventId = Number(id);
const { toast } = useToast();
const detailQuery = useQuery({
queryKey: ['admin', 'edit-event', eventId],
queryFn: () => api.getEventAdminDetail(eventId),
enabled: Boolean(eventId) && isAuthenticated,
});
const [formData, setFormData] = React.useState({
title: '',
status: 'draft',
event_type: 'online',
price: '',
capacity: '',
start_time: '',
end_time: '',
registration_start_date: '',
registration_end_date: '',
location: '',
address: '',
online_link: '',
description: '',
});
React.useEffect(() => {
if (detailQuery.data) {
const d = detailQuery.data as any;
setFormData({
title: d.title || '',
status: d.status || 'draft',
event_type: d.event_type || 'online',
price: d.price ? Math.floor(Number(d.price) / 10).toString() : '',
capacity: d.capacity != null ? String(d.capacity) : '',
start_time: toInputDateTime(d.start_time),
end_time: toInputDateTime(d.end_time),
registration_start_date: toInputDateTime(d.registration_start_date),
registration_end_date: toInputDateTime(d.registration_end_date),
location: d.location || '',
address: d.address || '',
online_link: d.online_link || '',
description: d.description || '',
});
}
}, [detailQuery.data]);
const updateMutation = useMutation({
mutationFn: (payload: any) => api.updateEvent(eventId, payload),
onSuccess: () => {
toast({ title: 'رویداد به‌روزرسانی شد', variant: 'success' });
queryClient.invalidateQueries({ queryKey: ['admin', 'edit-event', eventId] });
queryClient.invalidateQueries({ queryKey: ['admin', 'events'] });
navigate(`/admin/events/${eventId}`);
},
onError: (error) => {
toast({
variant: 'destructive',
title: 'خطا در ذخیره‌سازی رویداد',
description: resolveErrorMessage(error),
});
},
});
React.useEffect(() => {
if (detailQuery.error) {
toast({
variant: 'destructive',
title: 'خطا در دریافت رویداد',
description: resolveErrorMessage(detailQuery.error),
});
}
}, [detailQuery.error, toast]);
if (loading) {
return (
<div className="min-h-screen bg-background flex items-center justify-center">
<p className="text-muted-foreground">در حال بررسی دسترسی...</p>
</div>
);
}
if (!isAuthenticated || !(user?.is_staff || user?.is_superuser)) {
return <Navigate to="/" />;
}
return (
<div className="min-h-screen bg-background" dir="rtl">
<div className="container mx-auto px-4 py-10">
<Card>
<CardHeader>
<CardTitle>ویرایش رویداد</CardTitle>
<CardDescription>فرم کامل برای ویرایش جزئیات رویداد</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{detailQuery.isLoading ? (
<p className="text-sm text-muted-foreground">در حال بارگذاری جزئیات...</p>
) : detailQuery.data ? (
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
updateMutation.mutate({
title: formData.title,
status: formData.status,
event_type: formData.event_type,
price: formData.price ? Number(formData.price) * 10 : 0,
capacity: formData.capacity ? Number(formData.capacity) : null,
start_time: formData.start_time || null,
end_time: formData.end_time || null,
registration_start_date: formData.registration_start_date || null,
registration_end_date: formData.registration_end_date || null,
location: formData.location || null,
address: formData.address || null,
online_link: formData.online_link || null,
description: formData.description || '',
});
}}
>
<div className="grid gap-3 md:grid-cols-2">
<Input
placeholder="عنوان رویداد"
value={formData.title}
onChange={(e) => setFormData((p) => ({ ...p, title: e.target.value }))}
required
/>
<Select
value={formData.status}
onValueChange={(value) => setFormData((p) => ({ ...p, status: value }))}
>
<SelectTrigger>
<SelectValue placeholder="وضعیت" />
</SelectTrigger>
<SelectContent>
{statusOptions.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={formData.event_type}
onValueChange={(value) => setFormData((p) => ({ ...p, event_type: value }))}
>
<SelectTrigger>
<SelectValue placeholder="نوع رویداد" />
</SelectTrigger>
<SelectContent>
{typeOptions.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Input
placeholder="قیمت (تومان)"
value={formData.price}
onChange={(e) => setFormData((p) => ({ ...p, price: e.target.value }))}
/>
<Input
placeholder="ظرفیت"
value={formData.capacity}
onChange={(e) => setFormData((p) => ({ ...p, capacity: e.target.value }))}
/>
<Input
type="datetime-local"
placeholder="تاریخ شروع"
value={formData.start_time}
onChange={(e) => setFormData((p) => ({ ...p, start_time: e.target.value }))}
/>
<Input
type="datetime-local"
placeholder="تاریخ پایان"
value={formData.end_time}
onChange={(e) => setFormData((p) => ({ ...p, end_time: e.target.value }))}
/>
<Input
type="datetime-local"
placeholder="شروع ثبت‌نام"
value={formData.registration_start_date}
onChange={(e) => setFormData((p) => ({ ...p, registration_start_date: e.target.value }))}
/>
<Input
type="datetime-local"
placeholder="پایان ثبت‌نام"
value={formData.registration_end_date}
onChange={(e) => setFormData((p) => ({ ...p, registration_end_date: e.target.value }))}
/>
<Input
placeholder="محل برگزاری"
value={formData.location}
onChange={(e) => setFormData((p) => ({ ...p, location: e.target.value }))}
/>
<Input
placeholder="آدرس دقیق"
value={formData.address}
onChange={(e) => setFormData((p) => ({ ...p, address: e.target.value }))}
/>
<Input
placeholder="لینک آنلاین"
value={formData.online_link}
onChange={(e) => setFormData((p) => ({ ...p, online_link: e.target.value }))}
/>
</div>
<Textarea
placeholder="توضیحات رویداد"
value={formData.description}
onChange={(e) => setFormData((p) => ({ ...p, description: e.target.value }))}
rows={8}
/>
<div className="flex flex-wrap gap-2 justify-end">
<Button type="button" variant="outline" onClick={() => navigate(-1)}>
بازگشت
</Button>
<Button type="submit" disabled={updateMutation.isLoading}>
ذخیره
</Button>
</div>
</form>
) : (
<p className="text-sm text-destructive">امکان دریافت رویداد وجود ندارد.</p>
)}
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,270 @@
import * as React from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate } from 'react-router-dom';
import type { EventListItemSchema } from '@/lib/types';
import { api } from '@/lib/api';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/hooks/use-toast';
import { formatJalali, formatToman, getThumbUrl, resolveErrorMessage, toPersianDigits } from '@/lib/utils';
const EVENTS_PAGE_SIZE = 30;
const eventStatusOptions = [
{ value: 'all', label: 'همه وضعیت‌ها' },
{ value: 'draft', label: 'پیش‌نویس' },
{ value: 'published', label: 'منتشر شده' },
{ value: 'cancelled', label: 'لغو شده' },
{ value: 'completed', label: 'برگزار شده' },
];
const statusConfig: Record<
EventListItemSchema['status'],
{ label: string; variant: 'outline' | 'default' | 'destructive' | 'secondary' }
> = {
draft: { label: 'پیش‌نویس', variant: 'outline' },
published: { label: 'منتشر شده', variant: 'default' },
cancelled: { label: 'لغو شده', variant: 'destructive' },
completed: { label: 'برگزار شده', variant: 'secondary' },
};
const eventSortOptions = [
{ value: 'newest', label: 'جدیدترین شروع' },
{ value: 'oldest', label: 'قدیمی‌ترین شروع' },
{ value: 'priceAsc', label: 'قیمت صعودی' },
{ value: 'priceDesc', label: 'قیمت نزولی' },
];
const AdminEventsPage: React.FC = () => {
const { toast } = useToast();
const queryClient = useQueryClient();
const navigate = useNavigate();
const [filters, setFilters] = React.useState({
search: '',
status: 'all',
type: 'all',
sort: 'newest',
});
const eventsQuery = useQuery({
queryKey: ['admin', 'events', filters],
queryFn: () =>
api.getEvents({
statuses: filters.status === 'all' ? undefined : [filters.status],
event_type: filters.type === 'all' ? undefined : filters.type,
search: filters.search || undefined,
limit: EVENTS_PAGE_SIZE,
}),
});
const deleteMutation = useMutation({
mutationFn: (eventId: number) => api.deleteEvent(eventId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin', 'events'] });
toast({ title: 'رویداد حذف شد', variant: 'success' });
},
onError: (error) => {
toast({
title: 'خطا',
description: resolveErrorMessage(error),
variant: 'destructive',
});
},
});
const sortedEvents = React.useMemo(() => {
const list = (eventsQuery.data ?? []).slice();
switch (filters.sort) {
case 'newest':
return list.sort((a, b) => new Date(b.start_time).getTime() - new Date(a.start_time).getTime());
case 'oldest':
return list.sort((a, b) => new Date(a.start_time).getTime() - new Date(b.start_time).getTime());
case 'priceAsc':
return list.sort((a, b) => Number(a.price) - Number(b.price));
case 'priceDesc':
return list.sort((a, b) => Number(b.price) - Number(a.price));
default:
return list;
}
}, [eventsQuery.data, filters.sort]);
return (
<div className="space-y-6" dir="rtl">
<div className="flex flex-col gap-1">
<h2 className="text-xl font-semibold">رویدادها</h2>
<p className="text-sm text-muted-foreground">مدیریت رویدادها، ثبتنامها و وضعیت انتشار</p>
</div>
<Card>
<CardHeader>
<CardTitle>فیلترها</CardTitle>
<CardDescription>پیدا کردن سریع رویدادها</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
<Input
placeholder="عنوان رویداد..."
value={filters.search}
onChange={(event) => setFilters((prev) => ({ ...prev, search: event.target.value }))}
/>
<Select value={filters.status} onValueChange={(value) => setFilters((prev) => ({ ...prev, status: value }))}>
<SelectTrigger>
<SelectValue>
{eventStatusOptions.find((option) => option.value === filters.status)?.label ||
'وضعیت'}
</SelectValue>
</SelectTrigger>
<SelectContent>
{eventStatusOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={filters.type} onValueChange={(value) => setFilters((prev) => ({ ...prev, type: value }))}>
<SelectTrigger>
<SelectValue>
{{
all: 'همه انواع',
online: 'آنلاین',
on_site: 'حضوری',
hybrid: 'ترکیبی',
}[filters.type]}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">همه انواع</SelectItem>
<SelectItem value="online">آنلاین</SelectItem>
<SelectItem value="on_site">حضوری</SelectItem>
<SelectItem value="hybrid">ترکیبی</SelectItem>
</SelectContent>
</Select>
<Select value={filters.sort} onValueChange={(value) => setFilters((prev) => ({ ...prev, sort: value }))}>
<SelectTrigger>
<SelectValue>
{eventSortOptions.find((option) => option.value === filters.sort)?.label ||
'مرتب‌سازی'}
</SelectValue>
</SelectTrigger>
<SelectContent>
{eventSortOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>لیست رویدادها</CardTitle>
<CardDescription>وضعیت، ظرفیت و قیمت هر رویداد</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{eventsQuery.isLoading ? (
<p className="text-sm text-muted-foreground">در حال بارگذاری...</p>
) : sortedEvents.length === 0 ? (
<p className="text-sm text-muted-foreground">رویدادی یافت نشد.</p>
) : (
<div className="space-y-4">
<div className="hidden md:block">
<ScrollArea className="rounded-md border">
<table dir="rtl" className="w-full min-w-[780px] text-sm">
<thead className="text-xs uppercase text-muted-foreground">
<tr>
<th className="px-3 py-2 text-right">پوستر</th>
<th className="px-3 py-2 text-right">عنوان</th>
<th className="px-3 py-2 text-right">وضعیت</th>
<th className="px-3 py-2 text-right">تاریخ شروع</th>
<th className="px-3 py-2 text-right">ثبتنامها</th>
<th className="px-3 py-2 text-right">قیمت (تومان)</th>
<th className="px-3 py-2 text-right">عملیات</th>
</tr>
</thead>
<tbody>
{sortedEvents.map((event) => (
<tr key={event.id} className="border-b last:border-0 hover:bg-muted/50">
<td className="px-3 py-2 text-right">
<img
src={getThumbUrl(event)}
alt={event.title}
className="h-12 w-12 rounded object-cover"
loading="lazy"
/>
</td>
<td className="px-3 py-2 text-right cursor-pointer" onClick={() => navigate(`/admin/events/${event.id}`)}>
{event.title}
</td>
<td className="px-3 py-2 text-center">
<Badge variant={statusConfig[event.status].variant}>
{statusConfig[event.status].label}
</Badge>
</td>
<td className="px-3 py-2 text-right">{formatJalali(event.start_time)}</td>
<td className="px-3 py-2 text-right">{toPersianDigits(event.registration_count)}</td>
<td className="px-3 py-2 text-right">{formatToman(event.price)}</td>
<td className="px-3 py-2 text-left flex items-center gap-1">
<Button size="sm" variant="outline" onClick={() => navigate(`/admin/events/${event.id}`)}>
جزئیات
</Button>
<Button size="sm" variant="outline" asChild>
<Link to={`/admin/events/${event.id}/edit`}>ویرایش</Link>
</Button>
<Button
size="sm"
variant="destructive"
onClick={() => deleteMutation.mutate(event.id)}
>
حذف
</Button>
</td>
</tr>
))}
</tbody>
</table>
</ScrollArea>
</div>
<div className="grid gap-3 md:hidden">
{sortedEvents.map((event) => (
<div key={event.id} className="rounded-lg border p-3 space-y-2 bg-card">
<div className="flex items-center justify-between gap-2">
<div className="font-semibold text-right">{event.title}</div>
<Badge variant={statusConfig[event.status].variant}>{statusConfig[event.status].label}</Badge>
</div>
<div className="text-xs text-muted-foreground text-right space-y-1">
<div>تاریخ شروع: {formatJalali(event.start_time)}</div>
<div>ثبتنامها: {toPersianDigits(event.registration_count)}</div>
<div>قیمت: {formatToman(event.price)}</div>
</div>
<div className="flex items-center gap-2 justify-end">
<Button size="sm" variant="outline" onClick={() => navigate(`/admin/events/${event.id}`)}>
جزئیات
</Button>
<Button size="sm" variant="outline" asChild>
<Link to={`/admin/events/${event.id}/edit`}>ویرایش</Link>
</Button>
<Button size="sm" variant="destructive" onClick={() => deleteMutation.mutate(event.id)}>
حذف
</Button>
</div>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
};
export default AdminEventsPage;

View File

@@ -0,0 +1,60 @@
import { Outlet, Navigate, NavLink, useLocation } from 'react-router-dom';
import { useMemo } from 'react';
import { useAuth } from '@/contexts/AuthContext';
const navItems = [
{ to: '/admin/users', label: 'مدیریت کاربران' },
{ to: '/admin/events', label: 'مدیریت رویدادها' },
] as const;
export default function AdminLayout() {
const location = useLocation();
const { user, isAuthenticated, loading } = useAuth();
const isAdmin = useMemo(
() => isAuthenticated && Boolean(user?.is_staff || user?.is_superuser),
[isAuthenticated, user?.is_staff, user?.is_superuser],
);
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center text-muted-foreground" dir="rtl">
در حال بارگذاری...
</div>
);
}
if (!isAdmin) {
return <Navigate to="/" replace />;
}
return (
<div className="min-h-screen bg-background" dir="rtl">
<div className="border-b bg-muted/20">
<div className="container mx-auto flex items-center justify-between px-4 py-4 gap-4 flex-row-reverse md:flex-row">
<h1 className="text-2xl font-bold">پنل مدیریت</h1>
<div className="flex items-center gap-2">
{navItems.map((item) => (
<NavLink
key={item.to}
to={item.to}
className={({ isActive }) =>
[
'rounded-full px-4 py-2 text-sm transition',
(isActive || location.pathname.startsWith(item.to))
? 'bg-primary text-primary-foreground shadow'
: 'bg-card text-muted-foreground hover:text-foreground border',
].join(' ')
}
>
{item.label}
</NavLink>
))}
</div>
</div>
</div>
<div className="container mx-auto px-4 py-6">
<Outlet />
</div>
</div>
);
}

View File

@@ -0,0 +1,273 @@
import * as React from 'react';
import {
useQuery,
} from '@tanstack/react-query';
import type { UserListSchema } from '@/lib/types';
import { api } from '@/lib/api';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/hooks/use-toast';
import {
formatJalali,
formatNumberPersian,
resolveErrorMessage,
} from '@/lib/utils';
const USERS_PAGE_SIZE = 25;
const AdminUsersPage: React.FC = () => {
const { toast } = useToast();
const [filters, setFilters] = React.useState({
search: '',
studentId: '',
university: 'all',
major: 'all',
isActive: 'all',
});
const [page, setPage] = React.useState(1);
const majorsQuery = useQuery({
queryKey: ['majors'],
queryFn: () => api.getMajors(),
});
const universitiesQuery = useQuery({
queryKey: ['universities'],
queryFn: () => api.getUniversities(),
});
const usersQuery = useQuery({
queryKey: ['admin', 'users', filters, page],
queryFn: () =>
api.listUsers({
search: filters.search || undefined,
student_id: filters.studentId || undefined,
university: filters.university === 'all' ? undefined : filters.university,
major: filters.major === 'all' ? undefined : filters.major,
is_active:
filters.isActive === 'all'
? undefined
: filters.isActive === 'active'
? 'true'
: 'false',
limit: USERS_PAGE_SIZE,
offset: (page - 1) * USERS_PAGE_SIZE,
}),
});
const users = usersQuery.data ?? [];
const hasMore = users.length === USERS_PAGE_SIZE;
React.useEffect(() => {
if (usersQuery.error) {
toast({
title: 'خطا در بارگذاری کاربران',
description: resolveErrorMessage(usersQuery.error),
variant: 'destructive',
});
}
}, [usersQuery.error, toast]);
const handleFilterChange = (field: keyof typeof filters, value: string) => {
setFilters((prev) => ({ ...prev, [field]: value }));
setPage(1);
};
return (
<div className="space-y-6" dir="rtl">
<div>
<h2 className="text-xl font-semibold">کاربران</h2>
<p className="text-sm text-muted-foreground mt-1">مدیریت و جستجوی کاربران سامانه</p>
</div>
<Card>
<CardHeader>
<CardTitle>فیلترها</CardTitle>
<CardDescription>جستجو و محدود کردن نتایج</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
<Input
placeholder="نام، نام‌کاربری یا ایمیل..."
value={filters.search}
onChange={(event) => handleFilterChange('search', event.target.value)}
/>
<Input
placeholder="شماره دانشجویی"
value={filters.studentId}
onChange={(event) => handleFilterChange('studentId', event.target.value)}
/>
<Select value={filters.isActive} onValueChange={(value) => handleFilterChange('isActive', value)}>
<SelectTrigger>
<SelectValue placeholder="وضعیت">
{{
all: 'همه وضعیت‌ها',
active: 'فعال',
inactive: 'غیرفعال',
}[filters.isActive]}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">همه</SelectItem>
<SelectItem value="active">فعال</SelectItem>
<SelectItem value="inactive">غیرفعال</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-3 md:grid-cols-2">
<Select
value={filters.university}
onValueChange={(value) => handleFilterChange('university', value)}
>
<SelectTrigger>
<SelectValue placeholder="دانشگاه">
{filters.university === 'all'
? 'همه'
: universitiesQuery.data?.find((item) => item.code === filters.university)?.label}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">همه</SelectItem>
{universitiesQuery.data?.map((item) => (
<SelectItem key={item.code} value={item.code}>
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={filters.major} onValueChange={(value) => handleFilterChange('major', value)}>
<SelectTrigger>
<SelectValue placeholder="رشته">
{filters.major === 'all'
? 'همه'
: majorsQuery.data?.find((item) => item.code === filters.major)?.label}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">همه</SelectItem>
{majorsQuery.data?.map((item) => (
<SelectItem key={item.code} value={item.code}>
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-0 md:pb-2">
<CardTitle>لیست کاربران</CardTitle>
<CardDescription>نمایش کاربران مطابق فیلترهای انتخابی</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{usersQuery.isLoading ? (
<p className="text-sm text-muted-foreground">در حال بارگذاری...</p>
) : users.length === 0 ? (
<p className="text-sm text-muted-foreground">کاربری یافت نشد.</p>
) : (
<div className="space-y-3">
<ScrollArea className="rounded-md border hidden md:block">
<table dir="rtl" className="w-full min-w-[700px] text-sm">
<thead className="text-xs uppercase text-muted-foreground">
<tr>
<th className="px-3 py-2 text-right">نام کامل</th>
<th className="px-3 py-2 text-right">نام کاربری</th>
<th className="px-3 py-2 text-right">ایمیل</th>
<th className="px-3 py-2 text-right">دانشگاه / گرایش</th>
<th className="px-3 py-2 text-right">وضعیت</th>
<th className="px-3 py-2 text-right">تاریخ عضویت</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id} className="border-b last:border-0 hover:bg-muted/50">
<td className="px-3 py-2 text-right">
{(() => {
const parts = [user.first_name, user.last_name].filter(Boolean);
if (parts.length) return parts.join(' ');
return user.username;
})()}
</td>
<td className="px-3 py-2 text-right">{user.username}</td>
<td className="px-3 py-2 text-right">{user.email}</td>
<td className="px-3 py-2 text-right">
{user.major || '—'} · {user.university || '—'}
</td>
<td className="px-3 py-2 text-right">
<Badge variant={user.is_active ? 'default' : 'outline'}>
{user.is_active ? 'فعال' : 'غیرفعال'}
</Badge>
</td>
<td className="px-3 py-2 text-right">
{formatJalali(user.date_joined)}
</td>
</tr>
))}
</tbody>
</table>
</ScrollArea>
<div className="grid gap-3 md:hidden">
{users.map((user) => (
<div key={user.id} className="rounded-lg border p-3 space-y-2 bg-card">
<div className="flex items-center justify-between gap-2">
<div className="font-semibold text-right">{user.first_name || user.last_name ? `${user.first_name || ''} ${user.last_name || ''}`.trim() : user.username}</div>
<Badge variant={user.is_active ? 'default' : 'outline'}>{user.is_active ? 'فعال' : 'غیرفعال'}</Badge>
</div>
<div className="text-xs text-muted-foreground text-right space-y-1">
<div>نام کاربری: {user.username}</div>
<div>ایمیل: {user.email}</div>
<div>دانشگاه / گرایش: {user.university || '—'} · {user.major || '—'}</div>
<div>تاریخ عضویت: {formatJalali(user.date_joined)}</div>
</div>
</div>
))}
</div>
</div>
)}
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>صفحه {formatNumberPersian(page)}</span>
<div className="flex gap-2">
<Button
size="sm"
variant="outline"
disabled={page === 1}
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
>
قبلی
</Button>
<Button
size="sm"
variant="outline"
disabled={!hasMore}
onClick={() => setPage((prev) => prev + 1)}
>
بعدی
</Button>
</div>
</div>
</CardContent>
</Card>
</div>
);
};
export default AdminUsersPage;

549
frontend/src/pages/Auth.tsx Normal file
View File

@@ -0,0 +1,549 @@
import { useEffect, useState, useMemo } from 'react';
import { Helmet } from 'react-helmet-async';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import SearchableCombobox from '@/components/SearchableCombobox'
import { useToast } from '@/hooks/use-toast';
import { api } from '@/lib/api';
import { resolveErrorMessage } from '@/lib/utils';
type RegisterErrors = {
email?: string;
username?: string;
password?: string;
first_name?: string;
last_name?: string;
university?: string;
};
const MIN_PASSWORD_LENGTH = 8; // ← در صورت نیاز تغییر بده
const USERNAME_REGEX = /^[A-Za-z0-9._-]{3,30}$/; // ← کاراکترهای مجاز + حداقل 3 کاراکتر
const DISALLOW_PERSIAN_OR_SPACE = /[\u0600-\u06FF\s]/g; // ← حروف فارسی + فاصله
const sanitizeUsername = (v: string) => v.replace(/[^A-Za-z0-9._-]/g, '');
const sanitizeNoFaNoSpace = (v: string) => v.replace(DISALLOW_PERSIAN_OR_SPACE, '');
const isValidEmailBasic = (v: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
export default function Auth() {
const navigate = useNavigate();
const { login } = useAuth();
const { toast } = useToast();
const [loading, setLoading] = useState(false);
const [unverified, setUnverified] = useState(false);
const [resendLoading, setResendLoading] = useState(false);
const initialLogin = { email: '', password: '' };
const initialRegister = {
email: '',
password: '',
username: '',
first_name: '',
last_name: '',
student_id: '',
year_of_study: '',
major: null as string | null,
university: null as string | null,
};
const [loginData, setLoginData] = useState(initialLogin);
const [registerData, setRegisterData] = useState(initialRegister);
const [regErrors, setRegErrors] = useState<RegisterErrors>({});
const [tab, setTab] = useState<'login' | 'register'>('login');
const siteUrl = 'https://east-guilan-ce.ir';
const siteName = 'انجمن علمی کامپیوتر شرق دانشگاه گیلان';
const canonicalUrl = `${siteUrl}/auth`;
const ogImage = `${siteUrl}/favicon.ico`;
const metaRobots = 'noindex, nofollow';
const { pageTitle, pageDescription } = useMemo(() => {
const variant = tab === 'register' ? 'ثبت‌نام' : 'ورود';
const description =
tab === 'register'
? 'برای پیوستن به رویدادها، کارگاه‌ها و برنامه‌های انجمن علمی کامپیوتر شرق گیلان حساب کاربری بسازید.'
: 'برای مدیریت پروفایل و ثبت‌نام‌ رویدادها وارد انجمن علمی کامپیوتر شرق گیلان شوید.';
return {
pageTitle: `${variant} | ${siteName}`,
pageDescription: description,
};
}, [tab, siteName]);
const { data: majors, isLoading: majorsLoading } = useQuery({
queryKey: ['majors'],
queryFn: () => api.getMajors(), // expects [{ code, label }]
staleTime: 7 * 24 * 60 * 60 * 1000,
});
const { data: universities, isLoading: universitiesLoading } = useQuery({
queryKey: ['universities'],
queryFn: () => api.getUniversities(), // expects [{ code, label }]
staleTime: 7 * 24 * 60 * 60 * 1000,
});
const majorItems = useMemo(
() => (majors ?? []).map((m) => ({ value: String(m.code), label: m.label })),
[majors]
);
const universityItems = useMemo(
() => (universities ?? []).map((u) => ({ value: String(u.code), label: u.label })),
[universities]
);
// تبدیل ارقام فارسی/عربی به انگلیسی و حذف هرچیز غیر 0-9
const toEnglishDigits = (v: string) =>
v
.replace(/[\u06F0-\u06F9]/g, (d) => String(d.charCodeAt(0) - 0x06F0)) // Persian ۰
.replace(/[\u0660-\u0669]/g, (d) => String(d.charCodeAt(0) - 0x0660)); // Arabic ٠
const onlyAsciiDigits = (v: string) => toEnglishDigits(v).replace(/[^0-9]/g, '');
const handleResendVerification = async () => {
const email = sanitizeNoFaNoSpace(loginData.email.trim());
if (!email) {
toast({
title: 'ایمیل لازم است',
description: 'برای ارسال لینک تأیید، ابتدا ایمیل را وارد کنید.',
variant: 'destructive',
});
return;
}
if (!isValidEmailBasic(email)) {
toast({ title: 'ایمیل نامعتبر', description: 'فرمت ایمیل درست نیست.', variant: 'destructive' });
return;
}
try {
setResendLoading(true);
await api.resendVerification(email);
toast({
title: 'ایمیل ارسال شد',
description: 'اگر در صندوق ورودی نیست، پوشهٔ هرزنامه (اسپم) را بررسی کنید.',
variant: 'success',
});
} catch (error: unknown) {
toast({
title: 'خطا در ارسال',
description: resolveErrorMessage(error, 'مشکلی رخ داد'),
variant: 'destructive',
});
} finally {
setResendLoading(false);
}
};
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
const email = sanitizeNoFaNoSpace(loginData.email.trim());
const password = sanitizeNoFaNoSpace(loginData.password);
if (!email || !isValidEmailBasic(email)) {
throw new Error('ایمیل نامعتبر است.');
}
if (!password || DISALLOW_PERSIAN_OR_SPACE.test(loginData.password)) {
throw new Error('رمز عبور نباید شامل فاصله یا حروف فارسی باشد.');
}
await login(email, password);
toast({ title: 'خوش آمدید', description: 'با موفقیت وارد شدید', variant: 'success' });
navigate('/');
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
const isUnverified =
/please verify your email/i.test(msg) || // EN
/ایمیل.*تایید نشده|لطفاً.*ایمیل.*را.*تأیید/i.test(msg); // FA
if (isUnverified) {
setUnverified(true);
toast({
title: 'ایمیل شما تأیید نشده است',
description: 'برای ورود باید ایمیل را تأیید کنید. می‌توانید لینک تأیید را دوباره ارسال کنید.',
variant: 'destructive',
});
} else {
toast({ title: 'خطا', description: msg || 'خطا در ورود', variant: 'destructive' });
}
} finally {
setLoading(false);
}
};
const validateRegister = () => {
const errs: RegisterErrors = {};
const isBlank = (s: string) => !s || !s.trim();
const email = sanitizeNoFaNoSpace(registerData.email.trim());
const username = registerData.username.trim();
const password = registerData.password;
if (isBlank(email)) errs.email = 'ایمیل را وارد کنید';
else if (!isValidEmailBasic(email)) errs.email = 'فرمت ایمیل نامعتبر است';
else if (DISALLOW_PERSIAN_OR_SPACE.test(registerData.email)) errs.email = 'ایمیل نباید شامل فاصله یا حروف فارسی باشد';
if (isBlank(username)) errs.username = 'نام کاربری را وارد کنید';
else if (!USERNAME_REGEX.test(username)) errs.username = 'فقط حروف لاتین، اعداد، نقطه، آندرلاین و خط تیره (حداقل ۳ کاراکتر)';
if (isBlank(password)) errs.password = 'رمز عبور را وارد کنید';
else if (password.length < MIN_PASSWORD_LENGTH) errs.password = `حداقل ${MIN_PASSWORD_LENGTH} کاراکتر`;
else if (DISALLOW_PERSIAN_OR_SPACE.test(password)) errs.password = 'رمز عبور نباید شامل فاصله یا حروف فارسی باشد';
if (isBlank(registerData.first_name)) errs.first_name = 'نام را وارد کنید';
if (isBlank(registerData.last_name)) errs.last_name = 'نام خانوادگی را وارد کنید';
if (!registerData.university) errs.university = 'دانشگاه را انتخاب کنید';
setRegErrors(errs);
return Object.keys(errs).length === 0;
};
const handleRegister = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateRegister()) {
toast({ title: 'اطلاعات ناقص/نامعتبر', description: 'فیلدهای اجباری را درست تکمیل کنید.', variant: 'destructive' });
return;
}
setLoading(true);
try {
await api.register({
email: sanitizeNoFaNoSpace(registerData.email.trim()),
username: registerData.username.trim(),
password: registerData.password, // سرور هم اعتبارسنجی کند
first_name: registerData.first_name.trim(),
last_name: registerData.last_name.trim(),
student_id: registerData.student_id?.trim() || null,
year_of_study: registerData.year_of_study ? parseInt(registerData.year_of_study, 10) : null,
major: registerData.major || null,
university: registerData.university || null,
});
toast({
title: 'ثبت‌نام موفق',
description: 'ثبت‌نام با موفقیت انجام شد. لطفاً ایمیل خود را تأیید کنید.',
variant: 'success',
});
setTab('login');
setLoginData(() => ({ ...initialLogin, email: registerData.email }));
setRegisterData(initialRegister);
} catch (error) {
toast({
title: 'خطا',
description: error instanceof Error ? error.message : 'خطا در ثبت‌نام',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
const invalidClass = 'border-destructive focus-visible:ring-destructive';
// فقط اعداد برای سال ورودی
const onYearChange = (v: string) => v.replace(/\D/g, '');
useEffect(() => {
setTab('login');
}, []);
return (
<>
<Helmet>
<title>{pageTitle}</title>
<meta name="description" content={pageDescription} />
<meta name="robots" content={metaRobots} />
<link rel="canonical" href={canonicalUrl} />
<meta property="og:title" content={pageTitle} />
<meta property="og:description" content={pageDescription} />
<meta property="og:type" content="website" />
<meta property="og:url" content={canonicalUrl} />
<meta property="og:site_name" content={siteName} />
<meta property="og:image" content={ogImage} />
<meta property="og:locale" content="fa_IR" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={pageTitle} />
<meta name="twitter:description" content={pageDescription} />
<meta name="twitter:image" content={ogImage} />
</Helmet>
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardHeader dir="rtl">
<CardTitle>انجمن علمی کامپیوتر گیلان</CardTitle>
<CardDescription>ورود یا ثبتنام در سیستم</CardDescription>
</CardHeader>
<CardContent>
<Tabs value={tab} onValueChange={(v) => setTab(v as 'login' | 'register')} dir="rtl">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="login">ورود</TabsTrigger>
<TabsTrigger value="register">ثبتنام</TabsTrigger>
</TabsList>
{/* ورود */}
<TabsContent value="login">
<form onSubmit={handleLogin} className="space-y-4" noValidate>
<div>
<Label htmlFor="login-email">ایمیل</Label>
<Input
id="login-email"
name="username"
type="email"
inputMode="email"
autoComplete="username"
autoCorrect="off"
autoCapitalize="none"
spellCheck={false}
required
value={loginData.email}
onChange={(e) => setLoginData({ ...loginData, email: sanitizeNoFaNoSpace(e.target.value) })}
/>
</div>
<div>
<Label htmlFor="login-password">رمز عبور</Label>
<Input
id="login-password"
name="current-password"
type="password"
autoComplete="current-password"
autoCorrect="off"
autoCapitalize="none"
spellCheck={false}
required
value={loginData.password}
onChange={(e) => setLoginData({ ...loginData, password: sanitizeNoFaNoSpace(e.target.value) })}
/>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'در حال ورود...' : 'ورود'}
</Button>
<Link
to="/reset-password"
className="block text-xs text-muted-foreground hover:text-foreground underline underline-offset-4 text-right"
>
فراموشی رمز عبور؟
</Link>
<Button
type="button"
size="sm"
variant="secondary"
onClick={handleResendVerification}
disabled={resendLoading || !loginData.email}
className="min-w-40"
>
{resendLoading ? 'در حال ارسال...' : 'ارسال مجدد ایمیل تأیید'}
</Button>
{unverified && (
<div className="mt-3 text-right space-y-2">
<p className="text-sm text-muted-foreground">
حساب شما هنوز تأیید نشده است. لطفاً پوشهی اسپم ایمیل خود را بررسی کنید یا لینک تأیید را دوباره دریافت کنید.
</p>
</div>
)}
</form>
</TabsContent>
{/* ثبت‌نام */}
<TabsContent value="register">
<form onSubmit={handleRegister} className="space-y-4" noValidate>
<div>
<Label htmlFor="register-email">ایمیل</Label>
<Input
id="register-email"
type="email"
inputMode="email"
autoComplete="email"
autoCorrect="off"
autoCapitalize="none"
spellCheck={false}
value={registerData.email}
onChange={(e) => {
const val = sanitizeNoFaNoSpace(e.target.value);
setRegisterData({ ...registerData, email: val });
if (regErrors.email) setRegErrors((p) => ({ ...p, email: undefined }));
}}
className={regErrors.email ? invalidClass : undefined}
aria-invalid={!!regErrors.email}
/>
{regErrors.email && <p className="mt-1 text-xs text-destructive">{regErrors.email}</p>}
</div>
<div>
<Label htmlFor="register-username">نام کاربری</Label>
<Input
id="register-username"
type="text"
inputMode="text"
autoComplete="username"
autoCorrect="off"
autoCapitalize="none"
spellCheck={false}
placeholder="فقط حروف لاتین، اعداد، . _ -"
value={registerData.username}
onChange={(e) => {
const val = sanitizeUsername(e.target.value);
setRegisterData({ ...registerData, username: val });
if (regErrors.username) setRegErrors((p) => ({ ...p, username: undefined }));
}}
pattern="[A-Za-z0-9._-]{3,30}"
className={regErrors.username ? invalidClass : undefined}
aria-invalid={!!regErrors.username}
/>
{regErrors.username && <p className="mt-1 text-xs text-destructive">{regErrors.username}</p>}
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="register-first-name">نام</Label>
<Input
id="register-first-name"
type="text"
autoComplete="given-name"
value={registerData.first_name}
onChange={(e) => {
setRegisterData({ ...registerData, first_name: e.target.value });
if (regErrors.first_name) setRegErrors((p) => ({ ...p, first_name: undefined }));
}}
className={regErrors.first_name ? invalidClass : undefined}
aria-invalid={!!regErrors.first_name}
/>
{regErrors.first_name && <p className="mt-1 text-xs text-destructive">{regErrors.first_name}</p>}
</div>
<div>
<Label htmlFor="register-last-name">نام خانوادگی</Label>
<Input
id="register-last-name"
type="text"
autoComplete="family-name"
value={registerData.last_name}
onChange={(e) => {
setRegisterData({ ...registerData, last_name: e.target.value });
if (regErrors.last_name) setRegErrors((p) => ({ ...p, last_name: undefined }));
}}
className={regErrors.last_name ? invalidClass : undefined}
aria-invalid={!!regErrors.last_name}
/>
{regErrors.last_name && <p className="mt-1 text-xs text-destructive">{regErrors.last_name}</p>}
</div>
</div>
<div>
<Label htmlFor="register-university">دانشگاه</Label>
{universitiesLoading ? (
<div className="h-10 w-full animate-pulse rounded-md bg-muted" />
) : (
<>
<SearchableCombobox
items={universityItems}
value={registerData.university}
onChange={(v) => {
setRegisterData({ ...registerData, university: v });
if (regErrors.university) setRegErrors((p) => ({ ...p, university: undefined }));
}}
placeholder="انتخاب دانشگاه"
searchPlaceholder="نام دانشگاه را بنویسید…"
emptyText="دانشگاهی پیدا نشد"
className={regErrors.university ? "border-destructive focus-visible:ring-destructive" : undefined}
dir="rtl"
/>
{regErrors.university && (
<p className="mt-1 text-xs text-destructive">{regErrors.university}</p>
)}
</>
)}
</div>
<div>
<Label htmlFor="register-student-id">شماره دانشجویی (اختیاری)</Label>
<Input
id="register-student-id"
type="text"
inputMode="numeric"
pattern="[0-9]*"
dir="ltr"
value={registerData.student_id}
onChange={(e) =>
setRegisterData({ ...registerData, student_id: onlyAsciiDigits(e.target.value) })
}
onKeyDown={(e) => {
const allowed = ['Backspace','Delete','ArrowLeft','ArrowRight','Tab','Home','End'];
if (/^[0-9]$/.test(e.key)) return; // فقط 0-9
if (allowed.includes(e.key)) return; // کلیدهای کنترلی
if ((e.ctrlKey || e.metaKey) && ['a','c','v','x'].includes(e.key.toLowerCase())) return; // میانبرها
e.preventDefault(); // بقیه ممنوع
}}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="register-year">سال ورودی (اختیاری)</Label>
<Input
id="register-year"
type="text"
inputMode="numeric"
value={registerData.year_of_study}
onChange={(e) => setRegisterData({ ...registerData, year_of_study: onYearChange(e.target.value) })}
/>
</div>
<div>
<Label htmlFor="register-major">رشتهٔ تحصیلی (اختیاری)</Label>
{majorsLoading ? (
<div className="h-10 w-full animate-pulse rounded-md bg-muted" />
) : (
<SearchableCombobox
items={majorItems}
value={registerData.major}
onChange={(v) => setRegisterData({ ...registerData, major: v })}
placeholder="انتخاب رشته"
searchPlaceholder="نام رشته را بنویسید…"
emptyText="رشته‌ای پیدا نشد"
dir="rtl"
/>
)}
</div>
</div>
<div>
<Label htmlFor="register-password">رمز عبور</Label>
<Input
id="register-password"
type="password"
autoComplete="new-password"
autoCorrect="off"
autoCapitalize="none"
spellCheck={false}
value={registerData.password}
onChange={(e) => {
const val = sanitizeNoFaNoSpace(e.target.value);
setRegisterData({ ...registerData, password: val });
if (regErrors.password) setRegErrors((p) => ({ ...p, password: undefined }));
}}
className={regErrors.password ? invalidClass : undefined}
aria-invalid={!!regErrors.password}
/>
{regErrors.password ? (
<p className="mt-1 text-xs text-destructive">{regErrors.password}</p>
) : (
<p className="mt-1 text-[11px] text-muted-foreground">
حداقل {MIN_PASSWORD_LENGTH} کاراکتر بدون فاصله و حروف فارسی
</p>
)}
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'در حال ثبت‌نام...' : 'ثبت‌نام'}
</Button>
</form>
</TabsContent>
</Tabs>
</CardContent>
</Card>
</div>
</>
);
}

View File

@@ -0,0 +1,94 @@
import { useEffect, useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
interface Post {
id: number;
title: string;
slug: string;
excerpt?: string;
author: {
username: string;
first_name: string;
last_name: string;
};
created_at: string;
category?: {
name: string;
};
}
export default function Blog() {
const [posts, setPosts] = useState<Post[]>([]);
const [search, setSearch] = useState('');
const [loading, setLoading] = useState(true);
const loadPosts = useCallback(async () => {
try {
const data = await api.getPosts({ search: search || undefined });
setPosts(data as Post[]);
} catch (error) {
console.error('Error loading posts:', error);
} finally {
setLoading(false);
}
}, [search]);
useEffect(() => {
loadPosts();
}, [loadPosts]);
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto px-4 py-8">
<h1 className="text-4xl font-bold mb-8">وبلاگ</h1>
<div className="mb-8">
<Input
type="text"
placeholder="جستجو در مقالات..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="max-w-md"
/>
</div>
{loading ? (
<p className="text-center text-muted-foreground">در حال بارگذاری...</p>
) : posts.length === 0 ? (
<p className="text-center text-muted-foreground">مقالهای یافت نشد</p>
) : (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{posts.map((post) => (
<Link key={post.id} to={`/blog/${post.slug}`}>
<Card className="h-full hover:shadow-lg transition-shadow">
<CardHeader>
<CardTitle className="line-clamp-2">{post.title}</CardTitle>
<CardDescription>
{post.category?.name && (
<span className="text-primary ml-2">{post.category.name}</span>
)}
{new Date(post.created_at).toLocaleDateString('fa-IR')}
</CardDescription>
</CardHeader>
<CardContent>
{post.excerpt && (
<p className="text-muted-foreground line-clamp-3 mb-4">
{post.excerpt}
</p>
)}
<p className="text-sm">
نویسنده: {post.author.first_name} {post.author.last_name}
</p>
</CardContent>
</Card>
</Link>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,548 @@
import { useEffect, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useParams, useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type * as Types from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import Markdown from '@/components/Markdown';
import CouponDialogFa from '@/components/CouponDialogFa';
import { formatJalali, formatNumberPersian, formatToman, getThumbUrl, resolveErrorMessage, toPersianDigits } from '@/lib/utils';
import { useAuth } from '@/contexts/AuthContext';
const typeLabel: Record<string, string> = { online: 'آنلاین', on_site: 'حضوری', hybrid: 'آنلاین و حضوری' };
export default function EventDetail() {
const { slug } = useParams<{ slug: string }>();
const { isAuthenticated } = useAuth();
const navigate = useNavigate();
const { toast } = useToast();
const [event, setEvent] = useState<Types.EventDetailSchema | null>(null);
const [eventThumb, setEventThumb] = useState(null);
const [loading, setLoading] = useState(true);
const basePrice = Number(event?.price ?? 0);
const isFree = useMemo(() => basePrice <= 0, [basePrice]);
const [open, setOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const siteUrl = 'https://east-guilan-ce.ir';
const siteName = 'انجمن علمی کامپیوتر شرق گیلان';
const defaultDescription =
'جزئیات کامل رویدادهای انجمن علمی کامپیوتر شرق گیلان شامل زمان، مکان و شرایط ثبت‌نام.';
const toAbsoluteUrl = (url?: string | null) => {
if (!url) return undefined;
if (url.startsWith('http')) return url;
const normalizedSite = siteUrl.endsWith('/') ? siteUrl.slice(0, -1) : siteUrl;
const normalizedPath = url.startsWith('/') ? url.slice(1) : url;
return `${normalizedSite}/${normalizedPath}`;
};
const sanitizeDescription = (value?: string | null) => {
if (!value) return defaultDescription;
const stripped = value.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
if (!stripped) return defaultDescription;
if (stripped.length <= 160) return stripped;
return `${stripped.slice(0, 157)}...`;
};
const canonicalUrl = event ? `${siteUrl}/events/${event.slug}` : `${siteUrl}/events`;
const primaryImage = event
? toAbsoluteUrl(getThumbUrl(event)) ?? `${siteUrl}/favicon.ico`
: `${siteUrl}/favicon.ico`;
const pageTitle = event ? `${event.title} | ${siteName}` : `جزئیات رویداد | ${siteName}`;
const pageDescription = sanitizeDescription(event?.description);
const pageRobots = event?.status === 'draft' ? 'noindex, nofollow' : 'index, follow';
const [alreadyRegistered, setAlreadyRegistered] = useState(false);
useEffect(() => {
let cancelled = false;
async function check() {
if (isAuthenticated && event?.id) {
try {
const res = await api.getRegistrationStatus(event.id);
if (!cancelled) setAlreadyRegistered(res.is_registered);
} catch { /* ignore */ }
}
}
check();
return () => { cancelled = true; };
}, [isAuthenticated, event?.id]);
const goSuccess = (registrationId?: string) => {
const q = registrationId ? `?registration_id=${registrationId}` : '';
setAlreadyRegistered(true);
toast({ title: 'ثبت‌نام با موفقیت انجام شد!', variant: 'success' });
navigate(`/events/${event!.slug}/success${q}`);
};
const handleMainCTA = async () => {
if (!event) return;
if (!isAuthenticated) {
toast({ title: 'ابتدا وارد شوید', description: 'برای ثبت‌نام در رویداد باید وارد حساب کاربری خود شوید.', variant: 'destructive' });
navigate('/auth');
return;
}
if (isFree) {
try {
setSubmitting(true);
const res = await api.registerForEvent(event.id);
goSuccess(res.ticket_id);
} catch (error: unknown) {
const msg = resolveErrorMessage(error, '');
if (msg.includes('already registered') || msg.includes('ثبت‌نام')) {
setAlreadyRegistered(true);
toast({ title: 'شما قبلاً ثبت‌نام کرده‌اید', variant: 'destructive' });
return;
}
throw error;
} finally {
setSubmitting(false);
}
} else {
setOpen(true);
}
};
const handleContinueFromModal = async (coupon?: string, finalAmount?: number) => {
if (!event) return;
if (!isAuthenticated) {
toast({ title: 'ابتدا وارد شوید', description: 'برای ثبت‌نام در رویداد باید وارد حساب کاربری خود شوید.', variant: 'destructive' });
navigate('/auth');
return;
}
try {
setSubmitting(true);
const reg = await api.registerForEvent(event.id, coupon);
if (finalAmount === 0) {
sessionStorage.setItem('payment:last', JSON.stringify({
event_id: event.id,
slug: event.slug,
title: event.title,
thumb: eventThumb,
base_amount: Number(event.price ?? 0),
discount_amount: Number(event.price ?? 0),
amount: 0,
started_at: new Date().toISOString(),
success_markdown: event.registration_success_markdown,
}));
api.ChangeRegistrationStatus(reg.id, 'confirmed')
goSuccess(reg?.ticket_id);
return;
}
const description = `پرداخت رویداد: ${event.title}`;
const result = await api.createPayment({
event_id: event.id,
description,
discount_code: (coupon ?? '').trim() || null,
});
if (!result?.start_pay_url || Number(result.amount) === 0) {
sessionStorage.setItem('payment:last', JSON.stringify({
event_id: event.id,
slug: event.slug,
title: event.title,
thumb: eventThumb,
base_amount: result.base_amount,
discount_amount: result.discount_amount ?? result.base_amount,
amount: 0,
started_at: new Date().toISOString(),
success_markdown: event.registration_success_markdown,
}));
goSuccess(reg?.ticket_id);
return;
}
sessionStorage.setItem('payment:last', JSON.stringify({
event_id: event.id,
slug: event.slug,
title: event.title,
thumb: eventThumb,
base_amount: result.base_amount,
discount_amount: result.discount_amount,
amount: result.amount,
started_at: new Date().toISOString(),
success_markdown: event.registration_success_markdown,
}));
window.location.href = result.start_pay_url;
} catch (error: unknown) {
const msg = resolveErrorMessage(error, '');
if (msg.includes('already registered') || msg.includes('ثبت‌نام')) {
setAlreadyRegistered(true);
toast({ title: 'شما قبلاً ثبت‌نام کرده‌اید', variant: 'destructive' });
return;
}
toast({ title: 'خطا در پردازش پرداخت', description: msg || 'لطفاً دوباره تلاش کنید.', variant: 'destructive' });
} finally {
setSubmitting(false);
setOpen(false);
}
};
useEffect(() => {
(async () => {
try {
if (!slug) return;
const data = await api.getEventBySlug(slug);
setEvent(data);
setEventThumb(getThumbUrl(data));
} catch (error: unknown) {
toast({
title: 'خطا در بارگذاری رویداد',
description: resolveErrorMessage(error, 'لطفاً دوباره تلاش کنید.'),
variant: 'destructive',
});
} finally {
setLoading(false);
}
})();
}, [slug]);
const [nowTs, setNowTs] = useState(() => Date.now());
useEffect(() => {
const id = window.setInterval(() => setNowTs(Date.now()), 1000);
return () => window.clearInterval(id);
}, []);
const rsTs = useMemo<number | null>(() => (
event?.registration_start_date ? new Date(event.registration_start_date).getTime() : null
), [event?.registration_start_date]);
const deadlineTs = useMemo<number | null>(() => (
event?.registration_end_date ? new Date(event.registration_end_date).getTime() : null
), [event?.registration_end_date]);
const remainingMs = useMemo<number | null>(() => (
deadlineTs != null ? Math.max(0, deadlineTs - nowTs) : null
), [deadlineTs, nowTs]);
const formatCountdownTwoDigit = (value: number) =>
toPersianDigits(value.toString().padStart(2, '0'));
const formatCountdownNumber = (value: number) => formatNumberPersian(value);
const formatRemainingWords = (ms: number) => {
const total = Math.max(0, Math.floor(ms / 1000));
const days = Math.floor(total / 86400);
const hours = Math.floor((total % 86400) / 3600);
const minutes = Math.floor((total % 3600) / 60);
const seconds = total % 60;
if (days === 0) return `${formatCountdownTwoDigit(hours)} ساعت و ${formatCountdownTwoDigit(minutes)} دقیقه و ${formatCountdownTwoDigit(seconds)} ثانیه`;
return `${formatCountdownNumber(days)} روز و ${formatCountdownTwoDigit(hours)} ساعت و ${formatCountdownTwoDigit(minutes)} دقیقه و ${formatCountdownTwoDigit(seconds)} ثانیه`;
};
``
const meta = useMemo(() => {
if (!event) return null;
const rs = rsTs;
const re = deadlineTs;
const registrationOpen = (rs == null || nowTs >= rs) && (re == null || nowTs <= re);
const unlimited = event.capacity == null;
const remaining = unlimited ? Infinity : Math.max(0, (event.capacity || 0) - (event.registration_count || 0));
const full = !unlimited && remaining <= 0;
return { registrationOpen, remaining, full };
}, [event, rsTs, deadlineTs, nowTs]);
const eventStructuredData = useMemo(() => {
if (!event) return null;
const attendanceModeMap: Record<string, string> = {
online: 'https://schema.org/OnlineEventAttendanceMode',
on_site: 'https://schema.org/OfflineEventAttendanceMode',
hybrid: 'https://schema.org/MixedEventAttendanceMode',
};
const statusMap: Record<string, string> = {
published: 'https://schema.org/EventScheduled',
completed: 'https://schema.org/EventCompleted',
cancelled: 'https://schema.org/EventCancelled',
draft: 'https://schema.org/EventPostponed',
};
const data: Record<string, unknown> = {
'@context': 'https://schema.org',
'@type': 'Event',
name: event.title,
description: pageDescription,
startDate: event.start_time,
url: canonicalUrl,
eventAttendanceMode: attendanceModeMap[event.event_type] ?? attendanceModeMap.hybrid,
eventStatus: statusMap[event.status] ?? statusMap.published,
organizer: {
'@type': 'Organization',
name: siteName,
url: siteUrl,
},
};
if (event.end_time) {
data.endDate = event.end_time;
}
if (primaryImage) {
data.image = [primaryImage];
}
if (event.event_type === 'online') {
data.location = {
'@type': 'VirtualLocation',
url: event.online_link || canonicalUrl,
};
} else {
const location: Record<string, unknown> = {
'@type': 'Place',
name: event.location || event.address || siteName,
};
if (event.address) {
location.address = event.address;
}
if (event.location) {
location.description = event.location;
}
data.location = location;
}
const offers: Record<string, unknown> = {
'@type': 'Offer',
url: canonicalUrl,
priceCurrency: 'IRR',
price: String(event.price ?? 0),
availability: meta?.full ? 'https://schema.org/SoldOut' : 'https://schema.org/InStock',
};
if (event.registration_start_date) {
offers.validFrom = event.registration_start_date;
}
if (event.registration_end_date) {
offers.validThrough = event.registration_end_date;
}
data.offers = offers;
return data;
}, [event, pageDescription, canonicalUrl, primaryImage, meta?.full, siteName, siteUrl]);
const helmet = (
<Helmet>
<title>{pageTitle}</title>
<meta name="description" content={pageDescription} />
<meta name="robots" content={pageRobots} />
<link rel="canonical" href={canonicalUrl} />
<meta property="og:title" content={pageTitle} />
<meta property="og:description" content={pageDescription} />
<meta property="og:type" content="event" />
<meta property="og:url" content={canonicalUrl} />
<meta property="og:site_name" content={siteName} />
<meta property="og:image" content={primaryImage} />
<meta property="og:locale" content="fa_IR" />
{event?.start_time && <meta property="event:start_time" content={event.start_time} />}
{event?.end_time && <meta property="event:end_time" content={event.end_time} />}
{event?.updated_at && <meta property="og:updated_time" content={event.updated_at} />}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={pageTitle} />
<meta name="twitter:description" content={pageDescription} />
<meta name="twitter:image" content={primaryImage} />
{eventStructuredData && (
<script type="application/ld+json">{JSON.stringify(eventStructuredData)}</script>
)}
</Helmet>
);
const withHelmet = (node: JSX.Element) => (
<>
{helmet}
{node}
</>
);
if (loading) {
return withHelmet(
<div className="min-h-[60vh] flex items-center justify-center text-muted-foreground">در حال بارگذاری رویداد...</div>
);
}
if (!event) {
return withHelmet(
<div className="min-h-[60vh] flex items-center justify-center">رویداد مورد نظر یافت نشد.</div>
);
}
const beforeStart = rsTs != null && nowTs < rsTs;
const ended = deadlineTs !== null && remainingMs === 0;
const showCountdown = !beforeStart && deadlineTs !== null && remainingMs! > 0;
return withHelmet(
<div className="container mx-auto px-4 py-8" dir="rtl">
{/* --- نوار اطلاع/تایمر زیر نوار ناوبری با رنگ‌های مناسب Light/Dark --- */}
{beforeStart && (
<div className="mb-6">
<div className="rounded-xl border p-4 text-center bg-sky-50 text-sky-900 border-sky-200 dark:bg-sky-900/30 dark:text-sky-100 dark:border-sky-800">
ثبتنام از <strong className="font-semibold">{formatJalali(event.registration_start_date!)}</strong> آغاز میشود.
</div>
</div>
)}
{showCountdown && (
<div className="mb-6">
<div className="rounded-xl border p-4 text-center bg-emerald-50 text-emerald-900 border-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-100 dark:border-emerald-800">
<div className="flex flex-col items-center gap-1 sm:flex-row sm:justify-center">
<span>زمان باقیمانده تا پایان ثبتنام:</span>
<strong className="font-extrabold tracking-wider sm:ms-1">
{formatRemainingWords(remainingMs!)}
</strong>
</div>
</div>
</div>
)}
{ended && (
<div className="mb-6">
<div className="rounded-xl border p-4 text-center bg-rose-50 text-rose-900 border-rose-200 dark:bg-rose-900/30 dark:text-rose-100 dark:border-rose-800">
مهلت ثبتنام به پایان رسیده است.
</div>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* محتوا */}
<div className="lg:col-span-2">
<Card className="overflow-hidden">
<div className="w-full aspect-video overflow-hidden rounded-lg">
<img
src={getThumbUrl(event)}
alt={event.title}
className="w-full h-full object-cover"
loading="lazy"
decoding="async"
/>
</div>
<CardHeader>
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle className="text-2xl">{event.title}</CardTitle>
<CardDescription className="mt-1">
{formatJalali(event.start_time)}
{event.end_time ? ` تا ${formatJalali(event.end_time)}` : null}
</CardDescription>
</div>
<div className="flex flex-col items-end gap-2">
<Badge variant="default">{typeLabel[event.event_type] || event.event_type}</Badge>
</div>
</div>
</CardHeader>
<CardContent>
<Markdown content={event.description} justify size="base" />
</CardContent>
</Card>
{/* گالری */}
{event.gallery_images?.length ? (
<div className="mt-6">
<h3 className="text-lg font-semibold mb-3">گالری تصاویر</h3>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{event.gallery_images.map((g) => (
<img
key={g.id}
src={g.absolute_image_url || ''}
alt={g.title || ''}
className="w-full h-36 object-cover rounded-md"
/>
))}
</div>
</div>
) : null}
</div>
{/* سایدبار اطلاعات */}
<div className="lg:col-span-1">
<div className="lg:sticky lg:top-24">
<Card>
<CardHeader>
<CardTitle className="text-base">اطلاعات ثبتنام</CardTitle>
<CardDescription>جزئیات دسترسی به رویداد</CardDescription>
</CardHeader>
<CardContent className="space-y-3 text-sm">
{event.address && <div>آدرس: {event.address}</div>}
<div>ظرفیت کل: {event.capacity == null ? 'نامحدود' : formatNumberPersian(event.capacity)}</div>
{meta && (
<>
{!event.capacity ? null : (
<div>
ظرفیت باقیمانده: {meta.remaining === Infinity ? 'نامحدود' : formatNumberPersian(meta.remaining)}
</div>
)}
</>
)}
<div>هزینه حضور: {event.price ? formatToman(event.price) : 'رایگان'}</div>
{/* نمایش زمان شروع/پایان ثبت‌نام در UI حذف شده */}
<Button
onClick={handleMainCTA}
className="w-full mt-2"
disabled={
submitting ||
alreadyRegistered ||
event.status !== 'published' ||
meta?.full === true ||
!meta?.registrationOpen
}
>
{event.status !== 'published'
? 'ثبت‌نام این رویداد فعال نیست'
: alreadyRegistered
? 'شما قبلاً ثبت‌نام کرده‌اید'
: !meta?.registrationOpen
? 'ثبت‌نام هنوز آغاز نشده است'
: meta?.full
? 'ظرفیت ثبت‌نام تکمیل شده است'
: submitting
? 'در حال ثبت‌نام...'
: event.price === 0
? 'ثبت‌نام (رایگان)'
: 'ثبت‌نام و ادامه پرداخت'
}
</Button>
{!isFree && (
<CouponDialogFa
open={open}
onOpenChange={setOpen}
basePrice={basePrice}
onVerifyCouponRaw={(code) => api.checkDiscountCode(event.id, code)}
onContinue={handleContinueFromModal}
/>
)}
</CardContent>
</Card>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,154 @@
import { useLocation, useParams, Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import PaymentResult from "@/components/PaymentResult";
import { formatJalali } from "@/lib/utils";
import Markdown from '@/components/Markdown';
import { Helmet } from "react-helmet-async";
export default function EventFreeSuccessPage() {
const { slug } = useParams();
const search = new URLSearchParams(useLocation().search);
const registrationId = search.get("registration_id") || "";
const { data, isLoading, isError } = useQuery({
queryKey: ["registration-verify", registrationId],
queryFn: () =>
registrationId ? api.verifyMyRegistration(registrationId) : Promise.resolve(null),
enabled: Boolean(registrationId),
});
const registrationCodeFull = (data?.ticket_id || registrationId || "").trim();
const registrationCodeShort = registrationCodeFull
? (registrationCodeFull.split("-")[0] || registrationCodeFull).slice(0, 8)
: "";
const siteUrl = 'https://east-guilan-ce.ir';
const siteName = 'East Guilan CE';
const canonicalUrl = slug ? `${siteUrl}/events/${slug}/success` : `${siteUrl}/events`;
const registrationTitle = data?.event_title || slug || 'Event registration';
const ticketSummary = registrationCodeShort ? ` Ticket: ${registrationCodeShort}.` : '';
const pageState = isLoading
? 'Verifying registration'
: isError || !data
? 'Registration not found'
: 'Registration confirmed';
const pageTitle = `${pageState} | ${siteName}`;
const registrationCode = registrationId || 'your registration';
const pageDescription = data
? `Registration confirmed for ${registrationTitle}.${ticketSummary}`
: isError
? `We could not verify ${registrationCode}.`
: registrationId
? `Verifying registration ${registrationId} for ${registrationTitle}.`
: 'Review your registration status and ticket details.';
const helmet = (
<Helmet>
<title>{pageTitle}</title>
<meta name="description" content={pageDescription} />
<meta name="robots" content="noindex, nofollow" />
<link rel="canonical" href={canonicalUrl} />
<meta property="og:title" content={pageTitle} />
<meta property="og:description" content={pageDescription} />
<meta property="og:type" content="website" />
<meta property="og:url" content={canonicalUrl} />
<meta property="og:site_name" content={siteName} />
<meta property="og:image" content={`${siteUrl}/favicon.ico`} />
<meta property="og:locale" content="fa_IR" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content={pageTitle} />
<meta name="twitter:description" content={pageDescription} />
<meta name="twitter:image" content={`${siteUrl}/favicon.ico`} />
</Helmet>
);
const renderWithHelmet = (node: JSX.Element) => (
<>
{helmet}
{node}
</>
);
if (isLoading) {
return renderWithHelmet(
<div className="container py-10" dir="rtl">
در حال بارگذاری...
</div>
);
}
// اگر بک‌اند چیزی برنگرداند یا خطا داد
if (!data || isError) {
return renderWithHelmet(
<div className="container py-10" dir="rtl">
<PaymentResult
title="اطلاعات ثبت‌نام در دسترس نیست"
subtitle="امکان دریافت جزئیات ثبت‌نام فراهم نشد. اگر مبلغی پرداخت نشده، ثبت‌نام شما برای رویداد رایگان انجام شده است."
details={[
{ label: "کد ثبت‌نام", value: registrationCodeShort || "—" },
{ label: "رویداد", value: slug || "—" },
{ label: "مبلغ", value: "رایگان" },
]}
/>
<div className="mx-auto mt-6 flex max-w-xl items-center justify-end gap-2">
<Link to={`/events/${slug || ""}`}>
<Button variant="outline">بازگشت به رویداد</Button>
</Link>
<Link to="/events">
<Button>مشاهده سایر رویدادها</Button>
</Link>
</div>
</div>
);
}
const details = [
{ label: "عنوان رویداد", value: data.event_title || (slug || "—") },
{ label: "شیوه برگزاری", value: data.event_type || "—" },
{ label: "کد ثبت‌نام",
value: <code dir="ltr" className="font-mono bg-muted px-2 py-0.5 rounded">{registrationCodeShort || "—"}</code>
},
{ label: "وضعیت", value: faStatus(data.status) },
...(data.registered_at ? [{ label: "تاریخ ثبت‌نام", value: formatJalali(data.registered_at) }] : []),
{ label: "مبلغ", value: "رایگان" },
];
return renderWithHelmet(
<div className="container py-10" dir="rtl">
<PaymentResult
title="ثبت‌نام با موفقیت انجام شد 🎉"
subtitle={`شما با موفقیت برای «${data.event_title || "رویداد"}» ثبت‌نام کرده‌اید.`}
details={details}
/>
<div className="mx-auto mt-6 flex max-w-xl items-center justify-end gap-2">
<Markdown content={data.success_markdown} justify size="base" />
</div>
<div className="mx-auto mt-6 flex max-w-xl items-center justify-end gap-2">
<Link to={`/events/${slug || ""}`}>
<Button variant="outline">بازگشت به رویداد</Button>
</Link>
<Link to="/events">
<Button>مشاهده سایر رویدادها</Button>
</Link>
</div>
</div>
);
}
function faStatus(status?: string) {
switch ((status || "").toUpperCase()) {
case "CONFIRMED":
case "APPROVED":
return "تأیید شده";
case "PENDING":
return "در انتظار";
case "CANCELLED":
case "CANCELED":
return "لغو شده";
default:
return status || "—";
}
}

View File

@@ -0,0 +1,229 @@
import { useEffect, useState, useMemo, useCallback } from 'react';
import { Helmet } from 'react-helmet-async';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import type * as Types from '@/lib/types';
import { formatJalali, formatNumberPersian, formatToman, getThumbUrl } from '@/lib/utils';
function labelPrice(event: Types.EventListItemSchema) {
const price = Number(event?.price ?? 0);
return price <= 0 ? "رایگان" : formatToman(price);
}
function modeFa(event_type: Types.EventListItemSchema["event_type"]) {
return event_type === "online" ? "آنلاین" : "حضوری";
}
function spotsLeft(event: Types.EventListItemSchema) {
const cap = Number(event.capacity);
const used = Number(event.registration_count);
const left = cap - used;
return left;
}
function isAvailable(event: Types.EventListItemSchema) {
const now = new Date();
const end = new Date(event.registration_end_date);
const timeOk = end.getTime() > now.getTime();
const left = spotsLeft(event);
return timeOk && left > 0;
}
function notAvailableReasonFa(event: Types.EventListItemSchema) {
const now = new Date();
const end = new Date(event.registration_end_date);
if (end.getTime() <= now.getTime()) return "ثبت‌نام پایان‌یافته";
const left = spotsLeft(event);
if (left <= 0) return "ظرفیت تکمیل";
return "غیرقابل ثبت‌نام";
}
export default function Events() {
const [events, setEvents] = useState<Types.EventListItemSchema[]>([]);
const [search, setSearch] = useState('');
const [loading, setLoading] = useState(true);
const siteUrl = 'https://east-guilan-ce.ir';
const siteName = 'East Guilan CE';
const pageTitle = `Events | ${siteName}`;
const pageDescription =
'Discover upcoming and past events organized by the East Guilan Computer Engineering Association, including workshops, competitions, and community programs.';
const canonicalUrl = `${siteUrl}/events`;
const toAbsoluteUrl = (url?: string | null) => {
if (!url) return undefined;
if (url.startsWith('http')) return url;
const normalizedSite = siteUrl.endsWith('/') ? siteUrl.slice(0, -1) : siteUrl;
const normalizedPath = url.startsWith('/') ? url.slice(1) : url;
return `${normalizedSite}/${normalizedPath}`;
};
const ogImage = useMemo(() => {
if (!events.length) return `${siteUrl}/favicon.ico`;
return toAbsoluteUrl(getThumbUrl(events[0])) ?? `${siteUrl}/favicon.ico`;
}, [events]);
const listStructuredData = useMemo(() => {
if (!events.length) return null;
const itemListElement = events.map((eventItem, index) => {
const listItem: Record<string, unknown> = {
'@type': 'ListItem',
position: index + 1,
url: `${siteUrl}/events/${eventItem.slug}`,
name: eventItem.title,
description: eventItem.description,
startDate: eventItem.start_time,
};
if (eventItem.end_time) {
listItem.endDate = eventItem.end_time;
}
const imageUrl = toAbsoluteUrl(getThumbUrl(eventItem));
if (imageUrl) {
listItem.image = imageUrl;
}
const placeName = eventItem.location || eventItem.address;
if (placeName) {
const place: Record<string, unknown> = {
'@type': 'Place',
name: placeName,
};
if (eventItem.address) {
place.address = eventItem.address;
}
listItem.location = place;
}
return listItem;
});
return {
'@context': 'https://schema.org',
'@type': 'ItemList',
name: pageTitle,
description: pageDescription,
url: canonicalUrl,
numberOfItems: events.length,
itemListElement,
};
}, [events, canonicalUrl, pageDescription, pageTitle]);
const loadEvents = useCallback(async () => {
try {
setLoading(true);
const data = await api.getEvents({
search: search || undefined,
statuses: ['published', 'completed'],
limit: 30,
});
setEvents(data);
} catch (error) {
console.error('Error loading events:', error);
} finally {
setLoading(false);
}
}, [search]);
useEffect(() => {
loadEvents();
}, [loadEvents]);
return (
<>
<Helmet>
<title>{pageTitle}</title>
<meta name="description" content={pageDescription} />
<link rel="canonical" href={canonicalUrl} />
<meta property="og:title" content={pageTitle} />
<meta property="og:description" content={pageDescription} />
<meta property="og:type" content="website" />
<meta property="og:url" content={canonicalUrl} />
<meta property="og:site_name" content={siteName} />
<meta property="og:image" content={ogImage} />
<meta property="og:locale" content="fa_IR" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={pageTitle} />
<meta name="twitter:description" content={pageDescription} />
<meta name="twitter:image" content={ogImage} />
{listStructuredData && (
<script type="application/ld+json">{JSON.stringify(listStructuredData)}</script>
)}
</Helmet>
<div className="min-h-screen bg-background" dir="rtl">
<div className="container mx-auto px-4 py-8">
<h1 className="text-4xl font-bold mb-8">رویدادها</h1>
<div className="mb-8">
<Input
type="text"
placeholder="جستجو در رویدادها..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="max-w-md"
/>
</div>
{loading ? (
<p className="text-center text-muted-foreground">در حال بارگذاری...</p>
) : events.length === 0 ? (
<p className="text-center text-muted-foreground">رویدادی یافت نشد</p>
) : (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{events.map((event) => (
<Link key={event.id} to={`/events/${event.slug}`} className="block h-full">
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
<div className="w-full aspect-video overflow-hidden rounded-lg">
<img
src={getThumbUrl(event)}
alt={event.title}
className="w-full h-full object-cover"
loading="lazy"
decoding="async"
/>
</div>
{/* این رپر حالا قدِ باقی‌مانده رو می‌گیره */}
<div className="flex-1 flex flex-col justify-between">
<CardHeader>
<div className="flex items-start justify-between gap-2">
<CardTitle className="line-clamp-2">{event.title}</CardTitle>
<Badge variant="default">{modeFa(event.event_type)}</Badge>
</div>
<CardDescription>{formatJalali(event.start_time, false)}</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-1 text-sm" dir="rtl">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">ظرفیت رویداد</span>
<span className="font-medium">
{formatNumberPersian(Number(event?.capacity ?? 0) - Number(event?.registration_count ?? 0))}/{formatNumberPersian(Number(event?.capacity ?? 0))} نفر
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">هزینهی ثبتنام</span>
<span className="font-medium">{labelPrice(event)}</span>
</div>
{isAvailable(event) ? (
<Button>جزئیات رویداد</Button>
) : (
<Button variant="secondary">{notAvailableReasonFa(event)}</Button>
)}
</div>
</CardContent>
</div>
</Card>
</Link>
))}
</div>
)}
</div>
</div>
</>
);
}

130
frontend/src/pages/Home.tsx Normal file
View File

@@ -0,0 +1,130 @@
/**
* Home page highlighting the association mission, key offerings, and primary calls to action.
*/
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Helmet } from "react-helmet-async";
import { Link } from "react-router-dom";
const heroTitle = "انجمن علمی کامپیوتر دانشگاه گیلان";
const heroDescription =
"با ما همراه شوید و در دنیای مهندسی/علوم کامپیوتر و فناوری پیشرفت کنید. رویدادها، محتوای آموزشی و جامعه‌ای پویا برای رشد شما فراهم است.";
const structuredData = {
"@context": "https://schema.org",
"@type": "Organization",
name: heroTitle,
url: "https://east-guilan-ce.ir",
sameAs: ["https://east-guilan-ce.ir/blog", "https://east-guilan-ce.ir/events"],
description: heroDescription,
logo: "https://east-guilan-ce.ir/favicon.ico",
contactPoint: {
"@type": "ContactPoint",
email: "admin@east-guilan-ce.ir",
contactType: "customer support",
availableLanguage: ["fa", "en"]
}
};
export default function Home() {
return (
<>
<Helmet>
<title>{heroTitle}</title>
<meta name="description" content={heroDescription} />
<meta property="og:title" content={heroTitle} />
<meta property="og:description" content={heroDescription} />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://east-guilan-ce.ir" />
<meta property="og:image" content="https://east-guilan-ce.ir/favicon.ico" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={heroTitle} />
<meta name="twitter:description" content={heroDescription} />
<script type="application/ld+json">{JSON.stringify(structuredData)}</script>
</Helmet>
<main className="min-h-screen bg-background" dir="rtl">
<header className="bg-gradient-to-b from-primary/10 to-background py-20">
<div className="container mx-auto px-4 text-center">
<h1 className="mb-6 text-4xl font-extrabold leading-tight text-primary sm:text-5xl">{heroTitle}</h1>
<p className="mx-auto mb-10 max-w-2xl text-lg text-muted-foreground sm:text-xl">{heroDescription}</p>
<div className="flex flex-col items-center justify-center gap-4 sm:flex-row">
<Link to="/events">
<Button size="lg" aria-label="مشاهده رویدادهای انجمن">
مشاهده رویدادها
</Button>
</Link>
<Link to="/blog">
<Button size="lg" variant="outline" aria-label="مطالعه مقالات آموزشی">
خواندن مقالات
</Button>
</Link>
</div>
</div>
</header>
<section className="py-16" aria-labelledby="about-section">
<div className="container mx-auto px-4">
<h2 id="about-section" className="mb-12 text-center text-3xl font-bold">
درباره انجمن
</h2>
<div className="grid gap-8 md:grid-cols-3">
<Card>
<CardHeader>
<CardTitle>رویدادهای تخصصی</CardTitle>
<CardDescription>برگزاری کارگاهها، سمینارها و نشستهای علمی</CardDescription>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">
با شرکت در رویدادهای ما، دانش و مهارتهای خود را در کنار اساتید و متخصصان ارتقا دهید.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>مقالات آموزشی</CardTitle>
<CardDescription>دسترسی به مطالب آموزشی و پژوهشی باکیفیت</CardDescription>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">
تازهترین مقالات تخصصی در حوزههای مختلف علوم کامپیوتر برای یادگیری و توسعه فردی.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>جامعه فعال</CardTitle>
<CardDescription>ارتباط با دانشجویان و اساتید علاقهمند به فناوری</CardDescription>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">
به جامعهای پویا بپیوندید و از فرصتهای همکاری، شبکهسازی و رشد شخصی بهرهمند شوید.
</p>
</CardContent>
</Card>
</div>
</div>
</section>
<section className="bg-primary/5 py-16" aria-labelledby="cta-section">
<div className="container mx-auto px-4 text-center">
<h2 id="cta-section" className="mb-4 text-3xl font-bold">
آماده عضویت هستید؟
</h2>
<p className="mx-auto mb-8 max-w-xl text-muted-foreground">
همین حالا به جمع ما بپیوندید و از برنامهها و فرصتهای یادگیری انجمن علمی کامپیوتر دانشگاه گیلان استفاده کنید.
</p>
<Link to="/auth">
<Button size="lg" aria-label="ثبت نام در انجمن علمی کامپیوتر">
ثبتنام کنید
</Button>
</Link>
</div>
</section>
</main>
</>
);
}

View File

@@ -0,0 +1,14 @@
// Update this page (the content is just a fallback if you fail to update the page)
const Index = () => {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
<div className="text-center">
<h1 className="mb-4 text-4xl font-bold">Welcome to Your Blank App</h1>
<p className="text-xl text-muted-foreground">Start building your amazing project here!</p>
</div>
</div>
);
};
export default Index;

View File

@@ -0,0 +1,34 @@
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Loader2 } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
export default function Logout() {
const { logout } = useAuth();
const { toast } = useToast();
const navigate = useNavigate();
useEffect(() => {
let alive = true;
(async () => {
try {
await logout();
if (!alive) return;
toast({ title: "با موفقیت خارج شدید", variant: "destructive" });
} catch (e) {
// even if it fails, we still route to /auth
} finally {
if (alive) navigate("/auth", { replace: true });
}
})();
return () => { alive = false; };
}, [logout, navigate, toast]);
return (
<div className="min-h-[70vh] flex flex-col items-center justify-center gap-3 text-muted-foreground" dir="rtl">
<Loader2 className="h-6 w-6 animate-spin" />
<div>در حال خروج از حساب کاربری...</div>
</div>
);
}

View File

@@ -0,0 +1,25 @@
import { useLocation } from "react-router-dom";
import { useEffect } from "react";
import { toPersianDigits } from "@/lib/utils";
const NotFound = () => {
const location = useLocation();
useEffect(() => {
console.error("404 Error: User attempted to access non-existent route:", location.pathname);
}, [location.pathname]);
return (
<div className="flex min-h-screen items-center justify-center bg-gray-100">
<div className="text-center">
<h1 className="mb-4 text-4xl font-bold">{toPersianDigits("404")}</h1>
<p className="mb-4 text-xl text-gray-600">Oops! Page not found</p>
<a href="/" className="text-blue-500 underline hover:text-blue-700">
Return to Home
</a>
</div>
</div>
);
};
export default NotFound;

Some files were not shown because too many files have changed in this diff Show More