Initial P2P mobile frontend

- Copy P2P components from pwap/web
- Mobile-optimized P2P trading interface
- To be deployed at telegram.pezkuwichain.io/p2p
This commit is contained in:
2026-01-31 08:51:45 +03:00
commit bc7ab9b2a4
95 changed files with 12893 additions and 0 deletions
+24
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?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>pezkuwi-p2p-mobile</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+51
View File
@@ -0,0 +1,51 @@
{
"name": "pezkuwi-p2p-mobile",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint ."
},
"dependencies": {
"@pezkuwi/api": "^16.5.18",
"@pezkuwi/keyring": "^14.0.13",
"@pezkuwi/util": "^14.0.13",
"@pezkuwi/util-crypto": "^14.0.13",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-popover": "^1.1.1",
"@radix-ui/react-select": "^2.1.1",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-switch": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-tooltip": "^1.1.4",
"@supabase/supabase-js": "^2.49.4",
"@tanstack/react-query": "^5.56.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^3.6.0",
"lucide-react": "^0.462.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2",
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.11",
"typescript": "^5.5.3",
"vite": "^7.3.1"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+20
View File
@@ -0,0 +1,20 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { P2PDashboard } from './components/p2p/P2PDashboard';
import { AuthProvider } from './contexts/AuthContext';
import './index.css';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>
<div className="min-h-screen bg-background text-foreground">
<P2PDashboard />
</div>
</AuthProvider>
</QueryClientProvider>
);
}
export default App;
+311
View File
@@ -0,0 +1,311 @@
import React, { useState, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Loader2, Shield, Zap } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { TradeModal } from './TradeModal';
import { MerchantTierBadge } from './MerchantTierBadge';
import { getUserReputation, type P2PFiatOffer, type P2PReputation } from '@shared/lib/p2p-fiat';
import { supabase } from '@/lib/supabase';
import type { P2PFilters } from './types';
interface AdListProps {
type: 'buy' | 'sell' | 'my-ads';
filters?: P2PFilters;
}
interface OfferWithReputation extends P2PFiatOffer {
seller_reputation?: P2PReputation;
payment_method_name?: string;
merchant_tier?: 'lite' | 'super' | 'diamond';
}
export function AdList({ type, filters }: AdListProps) {
const { user } = useAuth();
const [offers, setOffers] = useState<OfferWithReputation[]>([]);
const [loading, setLoading] = useState(true);
const [selectedOffer, setSelectedOffer] = useState<OfferWithReputation | null>(null);
useEffect(() => {
fetchOffers();
// Refresh data when user returns to the tab (visibility change)
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
fetchOffers();
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [type, user, filters]);
const fetchOffers = async () => {
setLoading(true);
try {
let offersData: P2PFiatOffer[] = [];
// Build base query
let query = supabase.from('p2p_fiat_offers').select('*');
if (type === 'buy') {
// Buy tab = show SELL offers (user wants to buy from sellers)
query = query.eq('ad_type', 'sell').eq('status', 'open').gt('remaining_amount', 0);
} else if (type === 'sell') {
// Sell tab = show BUY offers (user wants to sell to buyers)
query = query.eq('ad_type', 'buy').eq('status', 'open').gt('remaining_amount', 0);
} else if (type === 'my-ads' && user) {
// My offers - show all of user's offers
query = query.eq('seller_id', user.id);
}
// Apply filters if provided
if (filters) {
// Token filter
if (filters.token && filters.token !== 'all') {
query = query.eq('token', filters.token);
}
// Fiat currency filter
if (filters.fiatCurrency && filters.fiatCurrency !== 'all') {
query = query.eq('fiat_currency', filters.fiatCurrency);
}
// Payment method filter
if (filters.paymentMethods && filters.paymentMethods.length > 0) {
query = query.in('payment_method_id', filters.paymentMethods);
}
// Amount range filter
if (filters.minAmount !== null) {
query = query.gte('remaining_amount', filters.minAmount);
}
if (filters.maxAmount !== null) {
query = query.lte('remaining_amount', filters.maxAmount);
}
// Sort order
const sortColumn = filters.sortBy === 'price' ? 'price_per_unit' :
filters.sortBy === 'completion_rate' ? 'created_at' :
filters.sortBy === 'trades' ? 'created_at' :
'created_at';
query = query.order(sortColumn, { ascending: filters.sortOrder === 'asc' });
} else {
query = query.order('created_at', { ascending: false });
}
const { data } = await query;
offersData = data || [];
// Enrich with reputation, payment method, and merchant tier
const enrichedOffers = await Promise.all(
offersData.map(async (offer) => {
const [reputation, paymentMethod, merchantTier] = await Promise.all([
getUserReputation(offer.seller_id),
supabase
.from('payment_methods')
.select('method_name')
.eq('id', offer.payment_method_id)
.single(),
supabase
.from('p2p_merchant_tiers')
.select('tier')
.eq('user_id', offer.seller_id)
.single()
]);
return {
...offer,
seller_reputation: reputation || undefined,
payment_method_name: paymentMethod.data?.method_name,
merchant_tier: merchantTier.data?.tier as 'lite' | 'super' | 'diamond' | undefined
};
})
);
// Apply client-side filters (completion rate, merchant tier)
let filteredOffers = enrichedOffers;
if (filters) {
// Completion rate filter (needs reputation data)
if (filters.minCompletionRate > 0) {
filteredOffers = filteredOffers.filter(offer => {
if (!offer.seller_reputation) return false;
const rate = (offer.seller_reputation.completed_trades / (offer.seller_reputation.total_trades || 1)) * 100;
return rate >= filters.minCompletionRate;
});
}
// Merchant tier filter
if (filters.merchantTiers && filters.merchantTiers.length > 0) {
filteredOffers = filteredOffers.filter(offer => {
if (!offer.merchant_tier) return false;
// If super is selected, include super and diamond
// If diamond is selected, include only diamond
if (filters.merchantTiers.includes('diamond')) {
return offer.merchant_tier === 'diamond';
}
if (filters.merchantTiers.includes('super')) {
return offer.merchant_tier === 'super' || offer.merchant_tier === 'diamond';
}
return filters.merchantTiers.includes(offer.merchant_tier);
});
}
// Verified only filter
if (filters.verifiedOnly) {
filteredOffers = filteredOffers.filter(offer => offer.seller_reputation?.verified_merchant);
}
}
setOffers(filteredOffers);
} catch (error) {
if (import.meta.env.DEV) console.error('Fetch offers error:', error);
} finally {
setLoading(false);
}
};
if (loading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-green-500" />
</div>
);
}
if (offers.length === 0) {
return (
<div className="text-center py-12">
<p className="text-gray-400">
{type === 'my-ads' ? 'You have no active offers' : 'No offers available'}
</p>
</div>
);
}
return (
<div className="space-y-4">
{offers.map(offer => (
<Card key={offer.id} className="bg-gray-900 border-gray-800 hover:border-gray-700 transition-colors">
<CardContent className="p-6">
<div className="grid grid-cols-1 md:grid-cols-5 gap-6 items-center">
{/* Seller Info */}
<div className="flex items-center gap-3">
<Avatar className="h-12 w-12">
<AvatarFallback className="bg-green-500/20 text-green-400">
{offer.seller_wallet.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<div className="flex items-center gap-2">
<p className="font-semibold text-white">
{offer.seller_wallet.slice(0, 6)}...{offer.seller_wallet.slice(-4)}
</p>
{offer.merchant_tier && (
<MerchantTierBadge tier={offer.merchant_tier} size="sm" />
)}
{offer.seller_reputation?.verified_merchant && (
<Shield className="w-4 h-4 text-blue-400" title="Verified Merchant" />
)}
{offer.seller_reputation?.fast_trader && (
<Zap className="w-4 h-4 text-yellow-400" title="Fast Trader" />
)}
</div>
{offer.seller_reputation && (
<p className="text-sm text-gray-400">
{offer.seller_reputation.completed_trades} trades {' '}
{((offer.seller_reputation.completed_trades / (offer.seller_reputation.total_trades || 1)) * 100).toFixed(0)}% completion
</p>
)}
</div>
</div>
{/* Price */}
<div>
<p className="text-sm text-gray-400">Price</p>
<p className="text-xl font-bold text-green-400">
{offer.price_per_unit.toFixed(2)} {offer.fiat_currency}
</p>
</div>
{/* Available */}
<div>
<p className="text-sm text-gray-400">Available</p>
<p className="text-lg font-semibold text-white">
{offer.remaining_amount} {offer.token}
</p>
{offer.min_order_amount && (
<p className="text-xs text-gray-500">
Min: {offer.min_order_amount} {offer.token}
</p>
)}
</div>
{/* Payment Method */}
<div>
<p className="text-sm text-gray-400">Payment</p>
<Badge variant="outline" className="mt-1">
{offer.payment_method_name || 'N/A'}
</Badge>
<p className="text-xs text-gray-500 mt-1">
{offer.time_limit_minutes} min limit
</p>
</div>
{/* Action */}
<div className="flex flex-col items-end gap-1">
{offer.seller_id === user?.id && type !== 'my-ads' && (
<Badge variant="outline" className="text-xs bg-blue-500/10 text-blue-400 border-blue-500/30">
Your Ad
</Badge>
)}
<Button
onClick={() => setSelectedOffer(offer)}
disabled={type === 'my-ads' || offer.seller_id === user?.id}
className="w-full md:w-auto"
title={offer.seller_id === user?.id ? "You can't trade with your own ad" : ''}
>
{type === 'buy' ? 'Buy' : 'Sell'} {offer.token}
</Button>
</div>
</div>
{/* Status badge for my-ads */}
{type === 'my-ads' && (
<div className="mt-4 pt-4 border-t border-gray-800">
<div className="flex items-center justify-between">
<Badge
variant={offer.status === 'open' ? 'default' : 'secondary'}
>
{offer.status.toUpperCase()}
</Badge>
<p className="text-sm text-gray-400">
Created: {new Date(offer.created_at).toLocaleDateString()}
</p>
</div>
</div>
)}
</CardContent>
</Card>
))}
{selectedOffer && (
<TradeModal
offer={selectedOffer}
onClose={() => {
setSelectedOffer(null);
fetchOffers(); // Refresh list
}}
/>
)}
</div>
);
}
+385
View File
@@ -0,0 +1,385 @@
/**
* Block Trade Component - OKX-Style OTC Trading
*
* Block trades are for large volume trades that are handled differently
* from regular P2P trades. They offer:
* - Custom pricing negotiation
* - Dedicated support
* - Multi-tranche settlements
* - Enhanced privacy
*/
import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Blocks, Shield, Clock, Lock, MessageSquare, ChevronRight,
Building2, AlertTriangle
} from 'lucide-react';
import { supabase } from '@/lib/supabase';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';
import type { CryptoToken, FiatCurrency } from '@pezkuwi/lib/p2p-fiat';
interface BlockTradeRequest {
id: string;
type: 'buy' | 'sell';
token: CryptoToken;
fiat_currency: FiatCurrency;
amount: number;
target_price?: number;
message?: string;
status: 'pending' | 'negotiating' | 'approved' | 'in_progress' | 'completed' | 'cancelled';
created_at: string;
}
const SUPPORTED_TOKENS: CryptoToken[] = ['HEZ', 'PEZ'];
// All supported fiat currencies including Kurdish Diaspora countries
const SUPPORTED_FIATS: { code: FiatCurrency; name: string; symbol: string; region: string }[] = [
// Primary regions (Kurdistan & neighboring)
{ code: 'TRY', name: 'Turkish Lira', symbol: '₺', region: 'Bakur' },
{ code: 'IQD', name: 'Iraqi Dinar', symbol: 'د.ع', region: 'Başûr' },
{ code: 'IRR', name: 'Iranian Rial', symbol: '﷼', region: 'Rojhilat' },
// Eurozone diaspora
{ code: 'EUR', name: 'Euro', symbol: '€', region: 'EU' },
// Other diaspora regions
{ code: 'USD', name: 'US Dollar', symbol: '$', region: 'USA' },
{ code: 'GBP', name: 'British Pound', symbol: '£', region: 'UK' },
{ code: 'SEK', name: 'Swedish Krona', symbol: 'kr', region: 'Sweden' },
{ code: 'CHF', name: 'Swiss Franc', symbol: 'Fr.', region: 'Switzerland' },
{ code: 'NOK', name: 'Norwegian Krone', symbol: 'kr', region: 'Norway' },
{ code: 'DKK', name: 'Danish Krone', symbol: 'kr', region: 'Denmark' },
{ code: 'AUD', name: 'Australian Dollar', symbol: 'A$', region: 'Australia' },
{ code: 'CAD', name: 'Canadian Dollar', symbol: 'C$', region: 'Canada' },
];
// Minimum amounts for block trade (in USD equivalent)
const MINIMUM_BLOCK_AMOUNTS: Record<CryptoToken, number> = {
HEZ: 10000, // 10,000 HEZ minimum
PEZ: 50000, // 50,000 PEZ minimum
};
export function BlockTrade() {
const [showRequestModal, setShowRequestModal] = useState(false);
const [type, setType] = useState<'buy' | 'sell'>('buy');
const [token, setToken] = useState<CryptoToken>('HEZ');
const [fiat, setFiat] = useState<FiatCurrency>('USD');
const [amount, setAmount] = useState('');
const [targetPrice, setTargetPrice] = useState('');
const [message, setMessage] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [requests, setRequests] = useState<BlockTradeRequest[]>([]);
const { user } = useAuth();
const fiatSymbol = SUPPORTED_FIATS.find(f => f.code === fiat)?.symbol || '';
const minAmount = MINIMUM_BLOCK_AMOUNTS[token];
// Fetch user's block trade requests
React.useEffect(() => {
if (!user) return;
const fetchRequests = async () => {
const { data, error } = await supabase
.from('p2p_block_trade_requests')
.select('*')
.eq('user_id', user.id)
.order('created_at', { ascending: false });
if (!error && data) {
setRequests(data);
}
};
fetchRequests();
}, [user]);
const handleSubmitRequest = async () => {
if (!user) {
toast.error('Please login to submit a block trade request');
return;
}
const amountNum = parseFloat(amount);
if (isNaN(amountNum) || amountNum < minAmount) {
toast.error(`Minimum amount for ${token} block trade is ${minAmount.toLocaleString()} ${token}`);
return;
}
setIsSubmitting(true);
try {
const { data, error } = await supabase
.from('p2p_block_trade_requests')
.insert({
user_id: user.id,
type,
token,
fiat_currency: fiat,
amount: amountNum,
target_price: targetPrice ? parseFloat(targetPrice) : null,
message: message || null,
status: 'pending'
})
.select()
.single();
if (error) throw error;
toast.success('Block trade request submitted! Our OTC desk will contact you within 24 hours.');
setShowRequestModal(false);
setAmount('');
setTargetPrice('');
setMessage('');
// Add to local state
setRequests(prev => [data, ...prev]);
} catch (err) {
console.error('Block trade request error:', err);
toast.error('Failed to submit request');
} finally {
setIsSubmitting(false);
}
};
const getStatusBadge = (status: BlockTradeRequest['status']) => {
const styles: Record<string, string> = {
pending: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
negotiating: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
approved: 'bg-green-500/20 text-green-400 border-green-500/30',
in_progress: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
completed: 'bg-gray-500/20 text-gray-400 border-gray-500/30',
cancelled: 'bg-red-500/20 text-red-400 border-red-500/30',
};
return styles[status] || styles.pending;
};
return (
<>
<Card className="bg-gradient-to-br from-purple-500/10 to-blue-500/10 border-purple-500/30">
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="p-2 bg-purple-500/20 rounded-lg">
<Blocks className="w-5 h-5 text-purple-400" />
</div>
<div>
<CardTitle className="text-lg text-white">Block Trade (OTC)</CardTitle>
<CardDescription className="text-gray-400">
Large volume trades with custom pricing
</CardDescription>
</div>
</div>
<Badge className="bg-purple-500/20 text-purple-400 border-purple-500/30">
VIP
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Features */}
<div className="grid grid-cols-2 gap-3">
<div className="flex items-center gap-2 text-sm text-gray-400">
<Lock className="w-4 h-4 text-purple-400" />
<span>Private Negotiation</span>
</div>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Shield className="w-4 h-4 text-green-400" />
<span>Escrow Protected</span>
</div>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Building2 className="w-4 h-4 text-blue-400" />
<span>Dedicated Support</span>
</div>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Clock className="w-4 h-4 text-yellow-400" />
<span>Flexible Settlement</span>
</div>
</div>
{/* Minimum Amounts Info */}
<div className="p-3 bg-gray-800/50 rounded-lg">
<p className="text-xs text-gray-500 mb-2">Minimum Block Trade Amounts:</p>
<div className="flex flex-wrap gap-2">
{Object.entries(MINIMUM_BLOCK_AMOUNTS).map(([t, min]) => (
<Badge key={t} variant="outline" className="border-gray-700 text-gray-300">
{min.toLocaleString()} {t}
</Badge>
))}
</div>
</div>
{/* Request Button */}
<Button
className="w-full bg-purple-600 hover:bg-purple-700"
onClick={() => setShowRequestModal(true)}
>
<MessageSquare className="w-4 h-4 mr-2" />
Request Block Trade
<ChevronRight className="w-4 h-4 ml-auto" />
</Button>
{/* Active Requests */}
{requests.length > 0 && (
<div className="space-y-2">
<p className="text-xs text-gray-500">Your Requests:</p>
{requests.slice(0, 3).map(req => (
<div
key={req.id}
className="p-2 bg-gray-800/50 rounded-lg flex items-center justify-between"
>
<div className="flex items-center gap-2">
<span className={`text-xs ${req.type === 'buy' ? 'text-green-400' : 'text-red-400'}`}>
{req.type.toUpperCase()}
</span>
<span className="text-sm text-white">
{req.amount.toLocaleString()} {req.token}
</span>
</div>
<Badge className={getStatusBadge(req.status)}>
{req.status.replace('_', ' ')}
</Badge>
</div>
))}
</div>
)}
</CardContent>
</Card>
{/* Request Modal */}
<Dialog open={showRequestModal} onOpenChange={setShowRequestModal}>
<DialogContent className="bg-gray-900 border-gray-800 max-w-md">
<DialogHeader>
<DialogTitle className="text-white flex items-center gap-2">
<Blocks className="w-5 h-5 text-purple-400" />
Block Trade Request
</DialogTitle>
<DialogDescription className="text-gray-400">
Submit a request for our OTC desk to handle your large volume trade.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{/* Buy/Sell Toggle */}
<Tabs value={type} onValueChange={(v) => setType(v as 'buy' | 'sell')}>
<TabsList className="grid w-full grid-cols-2 bg-gray-800">
<TabsTrigger value="buy" className="data-[state=active]:bg-green-600">
Buy
</TabsTrigger>
<TabsTrigger value="sell" className="data-[state=active]:bg-red-600">
Sell
</TabsTrigger>
</TabsList>
</Tabs>
{/* Token & Fiat */}
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="text-gray-400 text-xs">Token</Label>
<Select value={token} onValueChange={(v) => setToken(v as CryptoToken)}>
<SelectTrigger className="bg-gray-800 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
{SUPPORTED_TOKENS.map(t => (
<SelectItem key={t} value={t}>{t}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="text-gray-400 text-xs">Currency</Label>
<Select value={fiat} onValueChange={(v) => setFiat(v as FiatCurrency)}>
<SelectTrigger className="bg-gray-800 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
{SUPPORTED_FIATS.map(f => (
<SelectItem key={f.code} value={f.code}>
{f.symbol} {f.code}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Amount */}
<div>
<Label className="text-gray-400 text-xs">Amount ({token})</Label>
<Input
type="number"
placeholder={`Min: ${minAmount.toLocaleString()}`}
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="bg-gray-800 border-gray-700"
/>
<p className="text-xs text-gray-500 mt-1">
Minimum: {minAmount.toLocaleString()} {token}
</p>
</div>
{/* Target Price (Optional) */}
<div>
<Label className="text-gray-400 text-xs">Target Price (Optional)</Label>
<div className="relative">
<Input
type="number"
placeholder="Your desired price per unit"
value={targetPrice}
onChange={(e) => setTargetPrice(e.target.value)}
className="bg-gray-800 border-gray-700 pr-16"
/>
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm">
{fiatSymbol}/{token}
</span>
</div>
</div>
{/* Message */}
<div>
<Label className="text-gray-400 text-xs">Additional Details (Optional)</Label>
<Textarea
placeholder="Settlement preferences, timeline, payment methods..."
value={message}
onChange={(e) => setMessage(e.target.value)}
className="bg-gray-800 border-gray-700 min-h-[80px]"
/>
</div>
{/* Warning */}
<div className="p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-start gap-2">
<AlertTriangle className="w-4 h-4 text-yellow-400 mt-0.5" />
<p className="text-xs text-yellow-400">
Block trades require KYC verification and may take 24-48 hours to process.
Our OTC desk will contact you via email.
</p>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setShowRequestModal(false)}
className="border-gray-700"
>
Cancel
</Button>
<Button
className="bg-purple-600 hover:bg-purple-700"
onClick={handleSubmitRequest}
disabled={isSubmitting || !amount || parseFloat(amount) < minAmount}
>
{isSubmitting ? 'Submitting...' : 'Submit Request'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
+385
View File
@@ -0,0 +1,385 @@
import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useWallet } from '@/contexts/WalletContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { supabase } from '@/lib/supabase';
import {
getPaymentMethods,
validatePaymentDetails,
type PaymentMethod,
type FiatCurrency,
type CryptoToken
} from '@shared/lib/p2p-fiat';
interface CreateAdProps {
onAdCreated: () => void;
}
export function CreateAd({ onAdCreated }: CreateAdProps) {
const { user } = useAuth();
const { account } = useWallet();
const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<PaymentMethod | null>(null);
const [loading, setLoading] = useState(false);
// Form fields
const [adType, setAdType] = useState<'buy' | 'sell'>('sell');
const [token, setToken] = useState<CryptoToken>('HEZ');
const [amountCrypto, setAmountCrypto] = useState('');
const [fiatCurrency, setFiatCurrency] = useState<FiatCurrency>('TRY');
const [fiatAmount, setFiatAmount] = useState('');
const [paymentDetails, setPaymentDetails] = useState<Record<string, string>>({});
const [timeLimit, setTimeLimit] = useState(30);
const [minOrderAmount, setMinOrderAmount] = useState('');
const [maxOrderAmount, setMaxOrderAmount] = useState('');
// Load payment methods when currency changes
useEffect(() => {
const loadPaymentMethods = async () => {
const methods = await getPaymentMethods(fiatCurrency);
setPaymentMethods(methods);
setSelectedPaymentMethod(null);
setPaymentDetails({});
};
loadPaymentMethods();
}, [fiatCurrency]);
// Calculate price per unit
const pricePerUnit = amountCrypto && fiatAmount
? (parseFloat(fiatAmount) / parseFloat(amountCrypto)).toFixed(2)
: '0';
const handlePaymentMethodChange = (methodId: string) => {
const method = paymentMethods.find(m => m.id === methodId);
setSelectedPaymentMethod(method || null);
// Initialize payment details with empty values
if (method) {
const initialDetails: Record<string, string> = {};
Object.keys(method.fields).forEach(field => {
initialDetails[field] = '';
});
setPaymentDetails(initialDetails);
}
};
const handlePaymentDetailChange = (field: string, value: string) => {
setPaymentDetails(prev => ({ ...prev, [field]: value }));
};
const handleCreateAd = async () => {
console.log('🔥 handleCreateAd called', { account, user: user?.id });
if (!account || !user) {
toast.error('Please connect your wallet and log in');
console.log('❌ No account or user', { account, user });
return;
}
if (!selectedPaymentMethod) {
toast.error('Please select a payment method');
return;
}
// Validate payment details
const validation = validatePaymentDetails(
paymentDetails,
selectedPaymentMethod.validation_rules
);
if (!validation.valid) {
const firstError = Object.values(validation.errors)[0];
toast.error(firstError);
return;
}
// Validate amounts
const cryptoAmt = parseFloat(amountCrypto);
const fiatAmt = parseFloat(fiatAmount);
if (!cryptoAmt || cryptoAmt <= 0) {
toast.error('Invalid crypto amount');
return;
}
if (!fiatAmt || fiatAmt <= 0) {
toast.error('Invalid fiat amount');
return;
}
if (selectedPaymentMethod.min_trade_amount && fiatAmt < selectedPaymentMethod.min_trade_amount) {
toast.error(`Minimum trade amount: ${selectedPaymentMethod.min_trade_amount} ${fiatCurrency}`);
return;
}
if (selectedPaymentMethod.max_trade_amount && fiatAmt > selectedPaymentMethod.max_trade_amount) {
toast.error(`Maximum trade amount: ${selectedPaymentMethod.max_trade_amount} ${fiatCurrency}`);
return;
}
setLoading(true);
try {
// Insert offer into Supabase
// Note: payment_details_encrypted is stored as JSON string (encryption handled server-side in prod)
const { data, error } = await supabase
.from('p2p_fiat_offers')
.insert({
seller_id: user.id,
seller_wallet: account,
ad_type: adType,
token,
amount_crypto: cryptoAmt,
remaining_amount: cryptoAmt,
fiat_currency: fiatCurrency,
fiat_amount: fiatAmt,
payment_method_id: selectedPaymentMethod.id,
payment_details_encrypted: JSON.stringify(paymentDetails),
time_limit_minutes: timeLimit,
min_order_amount: minOrderAmount ? parseFloat(minOrderAmount) : null,
max_order_amount: maxOrderAmount ? parseFloat(maxOrderAmount) : null,
status: 'open'
})
.select()
.single();
if (error) {
console.error('❌ Supabase error:', error);
toast.error(error.message || 'Failed to create offer');
return;
}
console.log('✅ Offer created successfully:', data);
toast.success('Ad created successfully!');
onAdCreated();
} catch (error) {
if (import.meta.env.DEV) console.error('Create ad error:', error);
toast.error('Failed to create offer');
} finally {
setLoading(false);
}
};
return (
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="text-white">Create P2P Offer</CardTitle>
<CardDescription>
Lock your crypto in escrow and set your price
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Ad Type Selection */}
<div>
<Label>I want to</Label>
<div className="grid grid-cols-2 gap-2 mt-2">
<Button
type="button"
variant={adType === 'sell' ? 'default' : 'outline'}
className={adType === 'sell' ? 'bg-red-600 hover:bg-red-700' : ''}
onClick={() => setAdType('sell')}
>
Sell {token}
</Button>
<Button
type="button"
variant={adType === 'buy' ? 'default' : 'outline'}
className={adType === 'buy' ? 'bg-green-600 hover:bg-green-700' : ''}
onClick={() => setAdType('buy')}
>
Buy {token}
</Button>
</div>
<p className="text-xs text-gray-400 mt-1">
{adType === 'sell'
? 'You will receive fiat payment and send crypto to buyer'
: 'You will send fiat payment and receive crypto from seller'}
</p>
</div>
{/* Crypto Details */}
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="token">Token</Label>
<Select value={token} onValueChange={(v) => setToken(v as CryptoToken)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="HEZ">HEZ</SelectItem>
<SelectItem value="PEZ">PEZ</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="amountCrypto">Amount ({token})</Label>
<Input
id="amountCrypto"
type="number"
step="0.01"
value={amountCrypto}
onChange={e => setAmountCrypto(e.target.value)}
placeholder="Amount"
className="placeholder:text-gray-500 placeholder:opacity-50"
/>
</div>
</div>
{/* Fiat Details */}
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="fiatCurrency">Fiat Currency</Label>
<Select value={fiatCurrency} onValueChange={(v) => setFiatCurrency(v as FiatCurrency)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{/* Primary regions - Kurdistan & neighboring */}
<SelectItem value="TRY">🇹🇷 Turkish Lira (TRY) - Bakur</SelectItem>
<SelectItem value="IQD">🇮🇶 Iraqi Dinar (IQD) - Başûr</SelectItem>
<SelectItem value="IRR">🇮🇷 Iranian Rial (IRR) - Rojhilat</SelectItem>
{/* Eurozone diaspora */}
<SelectItem value="EUR">🇪🇺 Euro (EUR) - EU</SelectItem>
{/* Other diaspora regions */}
<SelectItem value="USD">🇺🇸 US Dollar (USD)</SelectItem>
<SelectItem value="GBP">🇬🇧 British Pound (GBP)</SelectItem>
<SelectItem value="SEK">🇸🇪 Swedish Krona (SEK)</SelectItem>
<SelectItem value="CHF">🇨🇭 Swiss Franc (CHF)</SelectItem>
<SelectItem value="NOK">🇳🇴 Norwegian Krone (NOK)</SelectItem>
<SelectItem value="DKK">🇩🇰 Danish Krone (DKK)</SelectItem>
<SelectItem value="AUD">🇦🇺 Australian Dollar (AUD)</SelectItem>
<SelectItem value="CAD">🇨🇦 Canadian Dollar (CAD)</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="fiatAmount">Total Amount ({fiatCurrency})</Label>
<Input
id="fiatAmount"
type="number"
step="0.01"
value={fiatAmount}
onChange={e => setFiatAmount(e.target.value)}
placeholder="Amount"
className="placeholder:text-gray-500 placeholder:opacity-50"
/>
</div>
</div>
{/* Price Display */}
{amountCrypto && fiatAmount && (
<div className="p-4 bg-green-500/10 border border-green-500/30 rounded-lg">
<p className="text-sm text-gray-400">Price per {token}</p>
<p className="text-2xl font-bold text-green-400">
{pricePerUnit} {fiatCurrency}
</p>
</div>
)}
{/* Payment Method */}
<div>
<Label htmlFor="paymentMethod">Payment Method</Label>
<Select onValueChange={handlePaymentMethodChange}>
<SelectTrigger>
<SelectValue placeholder="Select payment method..." />
</SelectTrigger>
<SelectContent>
{paymentMethods.map(method => (
<SelectItem key={method.id} value={method.id}>
{method.method_name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Dynamic Payment Details Fields */}
{selectedPaymentMethod && Object.keys(selectedPaymentMethod.fields).length > 0 && (
<div className="space-y-4 p-4 border border-gray-700 rounded-lg">
<h3 className="font-semibold text-white">Payment Details</h3>
{Object.entries(selectedPaymentMethod.fields).map(([field, placeholder]) => (
<div key={field}>
<Label htmlFor={field}>
{field.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
</Label>
<Input
id={field}
value={paymentDetails[field] || ''}
onChange={(e) => handlePaymentDetailChange(field, e.target.value)}
placeholder={placeholder}
className="placeholder:text-gray-500 placeholder:opacity-50"
/>
</div>
))}
</div>
)}
{/* Order Limits */}
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="minOrder">Min Order (optional)</Label>
<Input
id="minOrder"
type="number"
step="0.01"
value={minOrderAmount}
onChange={e => setMinOrderAmount(e.target.value)}
placeholder="Minimum amount (optional)"
className="placeholder:text-gray-500 placeholder:opacity-50"
/>
</div>
<div>
<Label htmlFor="maxOrder">Max Order (optional)</Label>
<Input
id="maxOrder"
type="number"
step="0.01"
value={maxOrderAmount}
onChange={e => setMaxOrderAmount(e.target.value)}
placeholder="Maximum amount (optional)"
className="placeholder:text-gray-500 placeholder:opacity-50"
/>
</div>
</div>
{/* Time Limit */}
<div>
<Label htmlFor="timeLimit">Payment Time Limit (minutes)</Label>
<Select value={timeLimit.toString()} onValueChange={(v) => setTimeLimit(parseInt(v))}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="15">15 minutes</SelectItem>
<SelectItem value="30">30 minutes</SelectItem>
<SelectItem value="60">1 hour</SelectItem>
<SelectItem value="120">2 hours</SelectItem>
</SelectContent>
</Select>
</div>
<Button
onClick={handleCreateAd}
className="w-full"
disabled={loading}
>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Creating offer & locking escrow...
</>
) : (
'Create Offer'
)}
</Button>
</CardContent>
</Card>
);
}
+450
View File
@@ -0,0 +1,450 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import {
Loader2,
Copy,
CheckCircle2,
AlertTriangle,
ExternalLink,
QrCode,
Wallet
} from 'lucide-react';
import { usePezkuwi } from '@/contexts/PezkuwiContext';
import { useWallet } from '@/contexts/WalletContext';
import { toast } from 'sonner';
import { supabase } from '@/lib/supabase';
import {
getPlatformWalletAddress,
type CryptoToken
} from '@shared/lib/p2p-fiat';
interface DepositModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess?: () => void;
}
type DepositStep = 'select' | 'send' | 'verify' | 'success';
export function DepositModal({ isOpen, onClose, onSuccess }: DepositModalProps) {
const { api, selectedAccount } = usePezkuwi();
const { balances, signTransaction } = useWallet();
const [step, setStep] = useState<DepositStep>('select');
const [token, setToken] = useState<CryptoToken>('HEZ');
const [amount, setAmount] = useState('');
const [platformWallet, setPlatformWallet] = useState<string>('');
const [txHash, setTxHash] = useState('');
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
const [verifying, setVerifying] = useState(false);
// Fetch platform wallet address on mount
useEffect(() => {
if (isOpen) {
fetchPlatformWallet();
}
}, [isOpen]);
const fetchPlatformWallet = async () => {
const address = await getPlatformWalletAddress();
setPlatformWallet(address);
};
const resetModal = () => {
setStep('select');
setToken('HEZ');
setAmount('');
setTxHash('');
setLoading(false);
setCopied(false);
setVerifying(false);
};
const handleClose = () => {
resetModal();
onClose();
};
const handleCopyAddress = async () => {
try {
await navigator.clipboard.writeText(platformWallet);
setCopied(true);
toast.success('Address copied to clipboard');
setTimeout(() => setCopied(false), 2000);
} catch {
toast.error('Failed to copy address');
}
};
const getAvailableBalance = () => {
if (token === 'HEZ') return balances.HEZ;
if (token === 'PEZ') return balances.PEZ;
return '0';
};
const handleSendDeposit = async () => {
if (!api || !selectedAccount) {
toast.error('Please connect your wallet');
return;
}
const depositAmount = parseFloat(amount);
if (isNaN(depositAmount) || depositAmount <= 0) {
toast.error('Please enter a valid amount');
return;
}
setLoading(true);
try {
// Build the transfer transaction
const DECIMALS = 12;
const amountBN = BigInt(Math.floor(depositAmount * 10 ** DECIMALS));
let tx;
if (token === 'HEZ') {
// Native transfer
tx = api.tx.balances.transferKeepAlive(platformWallet, amountBN);
} else {
// Asset transfer (PEZ = asset ID 1)
const assetId = token === 'PEZ' ? 1 : 0;
tx = api.tx.assets.transfer(assetId, platformWallet, amountBN);
}
toast.info('Please sign the transaction in your wallet...');
// Sign and send
const hash = await signTransaction(tx);
if (hash) {
setTxHash(hash);
setStep('verify');
toast.success('Transaction sent! Please verify your deposit.');
}
} catch (error: unknown) {
console.error('Deposit transaction error:', error);
const message = error instanceof Error ? error.message : 'Transaction failed';
toast.error(message);
} finally {
setLoading(false);
}
};
const handleVerifyDeposit = async () => {
if (!txHash) {
toast.error('Please enter the transaction hash');
return;
}
const depositAmount = parseFloat(amount);
if (isNaN(depositAmount) || depositAmount <= 0) {
toast.error('Invalid amount');
return;
}
setVerifying(true);
try {
// Call the Edge Function for secure deposit verification
// This verifies the transaction on-chain before crediting balance
const { data, error } = await supabase.functions.invoke('verify-deposit', {
body: {
txHash,
token,
expectedAmount: depositAmount
}
});
if (error) {
throw new Error(error.message || 'Verification failed');
}
if (data?.success) {
toast.success(`Deposit verified! ${data.amount} ${token} added to your balance.`);
setStep('success');
onSuccess?.();
} else {
throw new Error(data?.error || 'Verification failed');
}
} catch (error) {
console.error('Verify deposit error:', error);
const message = error instanceof Error ? error.message : 'Verification failed';
toast.error(message);
} finally {
setVerifying(false);
}
};
const renderStepContent = () => {
switch (step) {
case 'select':
return (
<div className="space-y-6">
<div className="space-y-2">
<Label>Select Token</Label>
<Select value={token} onValueChange={(v) => setToken(v as CryptoToken)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="HEZ">HEZ (Native)</SelectItem>
<SelectItem value="PEZ">PEZ</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Amount to Deposit</Label>
<div className="relative">
<Input
type="number"
placeholder="0.00"
value={amount}
onChange={(e) => setAmount(e.target.value)}
min="0"
step="0.0001"
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
{token}
</div>
</div>
<p className="text-xs text-muted-foreground">
Wallet Balance: {parseFloat(getAvailableBalance()).toFixed(4)} {token}
</p>
</div>
<Alert>
<Wallet className="h-4 w-4" />
<AlertDescription>
You will send {token} from your connected wallet to the P2P platform escrow.
After confirmation, the amount will be credited to your P2P internal balance.
</AlertDescription>
</Alert>
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={() => setStep('send')}
disabled={!amount || parseFloat(amount) <= 0}
>
Continue
</Button>
</DialogFooter>
</div>
);
case 'send':
return (
<div className="space-y-6">
<div className="p-4 rounded-lg bg-muted/50 border space-y-4">
<div className="text-center">
<div className="w-16 h-16 mx-auto mb-3 rounded-xl bg-primary/10 flex items-center justify-center">
<QrCode className="h-8 w-8 text-primary" />
</div>
<p className="text-sm font-medium">Send {amount} {token} to:</p>
</div>
{platformWallet ? (
<div className="space-y-2">
<div className="p-3 rounded-lg bg-background border font-mono text-xs break-all">
{platformWallet}
</div>
<Button
variant="outline"
size="sm"
className="w-full"
onClick={handleCopyAddress}
>
{copied ? (
<>
<CheckCircle2 className="h-4 w-4 mr-2 text-green-500" />
Copied!
</>
) : (
<>
<Copy className="h-4 w-4 mr-2" />
Copy Address
</>
)}
</Button>
</div>
) : (
<Skeleton className="h-16 w-full" />
)}
</div>
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Only send {token} on the PezkuwiChain network. Sending other tokens or using
other networks will result in permanent loss of funds.
</AlertDescription>
</Alert>
<div className="flex gap-2">
<Button
variant="outline"
className="flex-1"
onClick={() => setStep('select')}
>
Back
</Button>
<Button
className="flex-1"
onClick={handleSendDeposit}
disabled={loading || !platformWallet}
>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Sending...
</>
) : (
<>
Send {amount} {token}
</>
)}
</Button>
</div>
</div>
);
case 'verify':
return (
<div className="space-y-6">
<Alert>
<CheckCircle2 className="h-4 w-4 text-green-500" />
<AlertDescription>
Transaction sent! Please verify your deposit to credit your P2P balance.
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Transaction Hash</Label>
<div className="flex gap-2">
<Input
value={txHash}
onChange={(e) => setTxHash(e.target.value)}
placeholder="0x..."
className="font-mono text-xs"
/>
<Button
variant="outline"
size="icon"
onClick={() => window.open(`https://explorer.pezkuwichain.io/tx/${txHash}`, '_blank')}
disabled={!txHash}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="p-4 rounded-lg bg-muted/50 border">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<p className="text-muted-foreground">Token</p>
<p className="font-semibold">{token}</p>
</div>
<div>
<p className="text-muted-foreground">Amount</p>
<p className="font-semibold">{amount}</p>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={handleVerifyDeposit}
disabled={verifying || !txHash}
>
{verifying ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Verifying...
</>
) : (
'Verify Deposit'
)}
</Button>
</DialogFooter>
</div>
);
case 'success':
return (
<div className="space-y-6 text-center">
<div className="w-20 h-20 mx-auto rounded-full bg-green-500/10 flex items-center justify-center">
<CheckCircle2 className="h-10 w-10 text-green-500" />
</div>
<div>
<h3 className="text-xl font-semibold text-green-500">
Deposit Successful!
</h3>
<p className="text-muted-foreground mt-2">
{amount} {token} has been added to your P2P internal balance.
</p>
</div>
<div className="p-4 rounded-lg bg-muted/50 border">
<p className="text-sm text-muted-foreground">
You can now create sell offers or trade P2P using your internal balance.
No blockchain fees during P2P trades!
</p>
</div>
<Button onClick={handleClose} className="w-full">
Done
</Button>
</div>
);
}
};
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Deposit to P2P Balance
</DialogTitle>
{step !== 'success' && (
<DialogDescription>
{step === 'select' && 'Deposit crypto from your wallet to P2P internal balance'}
{step === 'send' && 'Send tokens to the platform escrow wallet'}
{step === 'verify' && 'Verify your transaction to credit your balance'}
</DialogDescription>
)}
</DialogHeader>
{renderStepContent()}
</DialogContent>
</Dialog>
);
}
+420
View File
@@ -0,0 +1,420 @@
import React, { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { AlertTriangle, Upload, X, FileText } from 'lucide-react';
import { supabase } from '@/lib/supabase';
import { toast } from 'sonner';
interface DisputeModalProps {
isOpen: boolean;
onClose: () => void;
tradeId: string;
counterpartyId: string;
counterpartyWallet: string;
isBuyer: boolean;
}
interface EvidenceFile {
id: string;
file: File;
preview?: string;
type: 'image' | 'document';
}
const DISPUTE_REASONS = [
{ value: 'payment_not_received', label: 'Payment not received' },
{ value: 'wrong_amount', label: 'Wrong amount received' },
{ value: 'seller_not_responding', label: 'Seller not responding' },
{ value: 'buyer_not_responding', label: 'Buyer not responding' },
{ value: 'fraudulent_behavior', label: 'Fraudulent behavior' },
{ value: 'fake_payment_proof', label: 'Fake payment proof' },
{ value: 'account_mismatch', label: 'Payment account name mismatch' },
{ value: 'other', label: 'Other' },
];
export function DisputeModal({
isOpen,
onClose,
tradeId,
counterpartyId,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
counterpartyWallet,
isBuyer,
}: DisputeModalProps) {
useTranslation();
const fileInputRef = useRef<HTMLInputElement>(null);
const [reason, setReason] = useState('');
const [description, setDescription] = useState('');
const [evidenceFiles, setEvidenceFiles] = useState<EvidenceFile[]>([]);
const [termsAccepted, setTermsAccepted] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
// Filter reasons based on role
const availableReasons = DISPUTE_REASONS.filter((r) => {
if (isBuyer) {
return r.value !== 'buyer_not_responding' && r.value !== 'payment_not_received';
} else {
return r.value !== 'seller_not_responding' && r.value !== 'fake_payment_proof';
}
});
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files) return;
const newFiles: EvidenceFile[] = [];
Array.from(files).forEach((file) => {
if (evidenceFiles.length + newFiles.length >= 5) {
toast.error('Maximum 5 evidence files allowed');
return;
}
if (file.size > 10 * 1024 * 1024) {
toast.error(`File ${file.name} is too large (max 10MB)`);
return;
}
const isImage = file.type.startsWith('image/');
const evidence: EvidenceFile = {
id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
file,
type: isImage ? 'image' : 'document',
};
if (isImage) {
evidence.preview = URL.createObjectURL(file);
}
newFiles.push(evidence);
});
setEvidenceFiles((prev) => [...prev, ...newFiles]);
// Reset input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
const removeEvidence = (id: string) => {
setEvidenceFiles((prev) => {
const file = prev.find((f) => f.id === id);
if (file?.preview) {
URL.revokeObjectURL(file.preview);
}
return prev.filter((f) => f.id !== id);
});
};
const uploadEvidence = async (disputeId: string): Promise<string[]> => {
const uploadedUrls: string[] = [];
for (const evidence of evidenceFiles) {
const fileName = `disputes/${disputeId}/${evidence.id}-${evidence.file.name}`;
const { data, error } = await supabase.storage
.from('p2p-evidence')
.upload(fileName, evidence.file);
if (error) {
console.error('Evidence upload failed:', error);
continue;
}
const { data: urlData } = supabase.storage
.from('p2p-evidence')
.getPublicUrl(data.path);
uploadedUrls.push(urlData.publicUrl);
}
return uploadedUrls;
};
const handleSubmit = async () => {
if (!reason) {
toast.error('Please select a reason');
return;
}
if (!description || description.length < 20) {
toast.error('Please provide a detailed description (at least 20 characters)');
return;
}
if (!termsAccepted) {
toast.error('Please accept the terms and conditions');
return;
}
setIsSubmitting(true);
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error('Not authenticated');
// Create dispute
const { data: dispute, error: disputeError } = await supabase
.from('p2p_disputes')
.insert({
trade_id: tradeId,
opened_by: user.id,
reason,
description,
status: 'open',
})
.select()
.single();
if (disputeError) throw disputeError;
// Upload evidence files
if (evidenceFiles.length > 0) {
const evidenceUrls = await uploadEvidence(dispute.id);
// Insert evidence records
const evidenceRecords = evidenceUrls.map((url, index) => ({
dispute_id: dispute.id,
uploaded_by: user.id,
evidence_type: evidenceFiles[index].type === 'image' ? 'screenshot' : 'document',
file_url: url,
description: `Evidence ${index + 1}`,
}));
await supabase.from('p2p_dispute_evidence').insert(evidenceRecords);
}
// Update trade status to disputed
await supabase
.from('p2p_fiat_trades')
.update({ status: 'disputed' })
.eq('id', tradeId);
// Create notification for counterparty
await supabase.from('p2p_notifications').insert({
user_id: counterpartyId,
type: 'dispute_opened',
title: 'Dispute Opened',
message: `A dispute has been opened for your trade. Reason: ${reason}`,
reference_type: 'dispute',
reference_id: dispute.id,
});
// Fetch admin user IDs and create notifications for each admin
const { data: adminIds, error: adminError } = await supabase.rpc('get_admin_user_ids');
if (adminError) {
console.error('Failed to fetch admin IDs:', adminError);
// Continue without admin notifications if fetching fails, but log the error
} else if (adminIds && adminIds.length > 0) {
const adminNotifications = adminIds.map((admin: { user_id: string }) => ({
user_id: admin.user_id,
type: 'dispute_opened',
title: 'New Dispute Requires Attention',
message: `Dispute #${dispute.id.slice(0, 8)} opened. Trade: ${tradeId.slice(0, 8)}`,
reference_type: 'dispute',
reference_id: dispute.id,
}));
await supabase.from('p2p_notifications').insert(adminNotifications);
}
toast.success('Dispute opened successfully');
onClose();
} catch (error) {
console.error('Failed to open dispute:', error);
toast.error('Failed to open dispute. Please try again.');
} finally {
setIsSubmitting(false);
}
};
const handleClose = () => {
// Cleanup previews
evidenceFiles.forEach((f) => {
if (f.preview) URL.revokeObjectURL(f.preview);
});
setReason('');
setDescription('');
setEvidenceFiles([]);
setTermsAccepted(false);
onClose();
};
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-red-500">
<AlertTriangle className="h-5 w-5" />
Open Dispute
</DialogTitle>
<DialogDescription>
Please provide details about the issue. Our support team will review your case
and contact both parties for resolution.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{/* Reason Selection */}
<div className="space-y-2">
<Label htmlFor="reason">Reason for Dispute *</Label>
<Select value={reason} onValueChange={setReason}>
<SelectTrigger>
<SelectValue placeholder="Select a reason..." />
</SelectTrigger>
<SelectContent>
{availableReasons.map((r) => (
<SelectItem key={r.value} value={r.value}>
{r.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="description">
Detailed Description * <span className="text-muted-foreground text-xs">(min 20 chars)</span>
</Label>
<Textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Please describe the issue in detail. Include relevant transaction IDs, timestamps, and any communication with the counterparty..."
rows={4}
maxLength={2000}
/>
<p className="text-xs text-muted-foreground text-right">
{description.length}/2000
</p>
</div>
{/* Evidence Upload */}
<div className="space-y-2">
<Label>Evidence (Optional - max 5 files, 10MB each)</Label>
<div className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-4">
<input
type="file"
ref={fileInputRef}
onChange={handleFileSelect}
accept="image/*,.pdf,.doc,.docx"
multiple
className="hidden"
/>
<div className="text-center">
<Upload className="h-8 w-8 mx-auto text-gray-400 mb-2" />
<Button
type="button"
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
disabled={evidenceFiles.length >= 5}
>
Upload Evidence
</Button>
<p className="text-xs text-muted-foreground mt-2">
Screenshots, bank statements, chat logs, receipts
</p>
</div>
</div>
{/* Evidence Preview */}
{evidenceFiles.length > 0 && (
<div className="grid grid-cols-2 gap-2 mt-2">
{evidenceFiles.map((evidence) => (
<div
key={evidence.id}
className="relative border rounded-lg p-2 flex items-center gap-2"
>
{evidence.type === 'image' ? (
<img
src={evidence.preview}
alt="Evidence"
className="w-10 h-10 object-cover rounded"
/>
) : (
<FileText className="w-10 h-10 text-blue-500" />
)}
<span className="text-xs truncate flex-1">
{evidence.file.name}
</span>
<button
onClick={() => removeEvidence(evidence.id)}
className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
</div>
{/* Warning Box */}
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
<div className="flex gap-2">
<AlertTriangle className="h-5 w-5 text-amber-500 shrink-0 mt-0.5" />
<div className="text-sm">
<p className="font-medium text-amber-800 dark:text-amber-200">
Important Notice
</p>
<ul className="text-amber-700 dark:text-amber-300 text-xs mt-1 space-y-1">
<li> False disputes may result in account restrictions</li>
<li> Resolution typically takes 1-3 business days</li>
<li> Both parties can submit evidence</li>
<li> Admin decision is final</li>
</ul>
</div>
</div>
</div>
{/* Terms Checkbox */}
<div className="flex items-start gap-2">
<Checkbox
id="terms"
checked={termsAccepted}
onCheckedChange={(checked) => setTermsAccepted(checked === true)}
/>
<Label htmlFor="terms" className="text-sm leading-tight cursor-pointer">
I confirm that the information provided is accurate and understand that
false claims may result in penalties.
</Label>
</div>
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={handleClose} disabled={isSubmitting}>
Cancel
</Button>
<Button
variant="destructive"
onClick={handleSubmit}
disabled={isSubmitting || !reason || !description || !termsAccepted}
>
{isSubmitting ? 'Submitting...' : 'Open Dispute'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+369
View File
@@ -0,0 +1,369 @@
/**
* Express Mode Component - OKX-Style Quick Trading
*
* Express mode allows users to quickly buy/sell crypto at the best available rate
* without manually selecting an offer. The system automatically matches with
* the best available merchant.
*/
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Zap, ArrowRight, Shield, Clock, Star, AlertCircle, CheckCircle2 } from 'lucide-react';
import { supabase } from '@/lib/supabase';
import { useAuth } from '@/contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import type { CryptoToken, FiatCurrency } from '@pezkuwi/lib/p2p-fiat';
interface BestOffer {
id: string;
seller_id: string;
price_per_unit: number;
remaining_amount: number;
payment_method_name: string;
seller_reputation: number;
seller_completed_trades: number;
time_limit_minutes: number;
}
interface ExpressModeProps {
onTradeStarted?: (tradeId: string) => void;
}
const SUPPORTED_TOKENS: CryptoToken[] = ['HEZ', 'PEZ'];
// All supported fiat currencies including Kurdish Diaspora countries
const SUPPORTED_FIATS: { code: FiatCurrency; name: string; symbol: string; region: string }[] = [
// Primary regions (Kurdistan & neighboring)
{ code: 'TRY', name: 'Turkish Lira', symbol: '₺', region: 'Bakur' },
{ code: 'IQD', name: 'Iraqi Dinar', symbol: 'د.ع', region: 'Başûr' },
{ code: 'IRR', name: 'Iranian Rial', symbol: '﷼', region: 'Rojhilat' },
// Eurozone diaspora
{ code: 'EUR', name: 'Euro', symbol: '€', region: 'EU' },
// Other diaspora regions
{ code: 'USD', name: 'US Dollar', symbol: '$', region: 'USA' },
{ code: 'GBP', name: 'British Pound', symbol: '£', region: 'UK' },
{ code: 'SEK', name: 'Swedish Krona', symbol: 'kr', region: 'Sweden' },
{ code: 'CHF', name: 'Swiss Franc', symbol: 'Fr.', region: 'Switzerland' },
{ code: 'NOK', name: 'Norwegian Krone', symbol: 'kr', region: 'Norway' },
{ code: 'DKK', name: 'Danish Krone', symbol: 'kr', region: 'Denmark' },
{ code: 'AUD', name: 'Australian Dollar', symbol: 'A$', region: 'Australia' },
{ code: 'CAD', name: 'Canadian Dollar', symbol: 'C$', region: 'Canada' },
];
export function ExpressMode({ onTradeStarted }: ExpressModeProps) {
const [mode, setMode] = useState<'buy' | 'sell'>('buy');
const [token, setToken] = useState<CryptoToken>('HEZ');
const [fiat, setFiat] = useState<FiatCurrency>('TRY');
const [amount, setAmount] = useState<string>('');
const [inputType, setInputType] = useState<'crypto' | 'fiat'>('fiat');
const [bestOffer, setBestOffer] = useState<BestOffer | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isProcessing, setIsProcessing] = useState(false);
const { user } = useAuth();
const navigate = useNavigate();
// Calculate conversion
const fiatSymbol = SUPPORTED_FIATS.find(f => f.code === fiat)?.symbol || '';
const cryptoAmount = inputType === 'crypto'
? parseFloat(amount) || 0
: bestOffer ? (parseFloat(amount) || 0) / bestOffer.price_per_unit : 0;
const fiatAmount = inputType === 'fiat'
? parseFloat(amount) || 0
: bestOffer ? (parseFloat(amount) || 0) * bestOffer.price_per_unit : 0;
// Fetch best offer when parameters change
useEffect(() => {
const fetchBestOffer = async () => {
if (!amount || parseFloat(amount) <= 0) {
setBestOffer(null);
return;
}
setIsLoading(true);
try {
// Get best offer based on mode
const { data, error } = await supabase
.from('p2p_fiat_offers')
.select(`
id,
seller_id,
price_per_unit,
remaining_amount,
time_limit_minutes,
payment_methods!inner(method_name),
profiles!p2p_fiat_offers_seller_id_fkey(display_name),
p2p_reputation!p2p_fiat_offers_seller_id_fkey(reputation_score, completed_trades)
`)
.eq('token', token)
.eq('fiat_currency', fiat)
.eq('status', 'open')
.gt('remaining_amount', 0)
.order('price_per_unit', { ascending: mode === 'buy' })
.limit(1)
.single();
if (error) {
setBestOffer(null);
} else if (data) {
setBestOffer({
id: data.id,
seller_id: data.seller_id,
price_per_unit: data.price_per_unit,
remaining_amount: data.remaining_amount,
payment_method_name: (data.payment_methods as { method_name?: string })?.method_name || 'Bank Transfer',
seller_reputation: (data.p2p_reputation as { reputation_score?: number })?.reputation_score || 0,
seller_completed_trades: (data.p2p_reputation as { completed_trades?: number })?.completed_trades || 0,
time_limit_minutes: data.time_limit_minutes,
});
}
} catch (err) {
console.error('Fetch best offer error:', err);
setBestOffer(null);
} finally {
setIsLoading(false);
}
};
const debounce = setTimeout(fetchBestOffer, 300);
return () => clearTimeout(debounce);
}, [amount, token, fiat, mode]);
// Handle express trade
const handleExpressTrade = async () => {
if (!user) {
toast.error('Please login to trade');
return;
}
if (!bestOffer) {
toast.error('No offers available');
return;
}
if (cryptoAmount > bestOffer.remaining_amount) {
toast.error(`Maximum available: ${bestOffer.remaining_amount} ${token}`);
return;
}
setIsProcessing(true);
try {
// Accept the best offer
const { data: result, error } = await supabase.rpc('accept_p2p_offer', {
p_offer_id: bestOffer.id,
p_buyer_id: user.id,
p_buyer_wallet: '', // Will be set from user profile
p_amount: cryptoAmount
});
if (error) throw error;
const response = typeof result === 'string' ? JSON.parse(result) : result;
if (!response.success) {
throw new Error(response.error || 'Failed to start trade');
}
toast.success('Express trade started!');
if (onTradeStarted) {
onTradeStarted(response.trade_id);
} else {
navigate(`/p2p/trade/${response.trade_id}`);
}
} catch (err) {
console.error('Express trade error:', err);
toast.error(err instanceof Error ? err.message : 'Failed to start trade');
} finally {
setIsProcessing(false);
}
};
return (
<Card className="bg-gradient-to-br from-yellow-500/10 to-orange-500/10 border-yellow-500/30">
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="p-2 bg-yellow-500/20 rounded-lg">
<Zap className="w-5 h-5 text-yellow-400" />
</div>
<div>
<CardTitle className="text-lg text-white">Express Mode</CardTitle>
<p className="text-xs text-gray-400">Instant best-rate matching</p>
</div>
</div>
<Badge className="bg-yellow-500/20 text-yellow-400 border-yellow-500/30">
Fast
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Buy/Sell Toggle */}
<Tabs value={mode} onValueChange={(v) => setMode(v as 'buy' | 'sell')}>
<TabsList className="grid w-full grid-cols-2 bg-gray-800">
<TabsTrigger value="buy" className="data-[state=active]:bg-green-600">
Buy {token}
</TabsTrigger>
<TabsTrigger value="sell" className="data-[state=active]:bg-red-600">
Sell {token}
</TabsTrigger>
</TabsList>
</Tabs>
{/* Token & Fiat Selection */}
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="text-gray-400 text-xs">Crypto</Label>
<Select value={token} onValueChange={(v) => setToken(v as CryptoToken)}>
<SelectTrigger className="bg-gray-800 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
{SUPPORTED_TOKENS.map(t => (
<SelectItem key={t} value={t}>{t}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="text-gray-400 text-xs">Currency</Label>
<Select value={fiat} onValueChange={(v) => setFiat(v as FiatCurrency)}>
<SelectTrigger className="bg-gray-800 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
{SUPPORTED_FIATS.map(f => (
<SelectItem key={f.code} value={f.code}>
{f.symbol} {f.code}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Amount Input */}
<div>
<div className="flex items-center justify-between mb-1">
<Label className="text-gray-400 text-xs">
{inputType === 'fiat' ? `Amount (${fiat})` : `Amount (${token})`}
</Label>
<Button
variant="ghost"
size="sm"
className="text-xs text-yellow-400 h-auto p-0"
onClick={() => setInputType(inputType === 'fiat' ? 'crypto' : 'fiat')}
>
Switch to {inputType === 'fiat' ? token : fiat}
</Button>
</div>
<div className="relative">
<Input
type="number"
placeholder="0.00"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="bg-gray-800 border-gray-700 text-lg pr-16"
/>
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">
{inputType === 'fiat' ? fiatSymbol : token}
</span>
</div>
</div>
{/* Conversion Display */}
{bestOffer && parseFloat(amount) > 0 && (
<div className="p-3 bg-gray-800/50 rounded-lg space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-gray-400">You {mode === 'buy' ? 'pay' : 'receive'}</span>
<span className="text-white font-medium">
{fiatSymbol}{fiatAmount.toLocaleString(undefined, { maximumFractionDigits: 2 })} {fiat}
</span>
</div>
<div className="flex items-center justify-center">
<ArrowRight className="w-4 h-4 text-gray-500" />
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-gray-400">You {mode === 'buy' ? 'receive' : 'send'}</span>
<span className="text-white font-medium">
{cryptoAmount.toLocaleString(undefined, { maximumFractionDigits: 6 })} {token}
</span>
</div>
<div className="pt-2 border-t border-gray-700 space-y-1">
<div className="flex items-center justify-between text-xs">
<span className="text-gray-500">Rate</span>
<span className="text-gray-300">
1 {token} = {fiatSymbol}{bestOffer.price_per_unit.toLocaleString()}
</span>
</div>
<div className="flex items-center justify-between text-xs">
<span className="text-gray-500">Merchant Rating</span>
<span className="text-yellow-400 flex items-center gap-1">
<Star className="w-3 h-3" />
{bestOffer.seller_reputation}% ({bestOffer.seller_completed_trades} trades)
</span>
</div>
<div className="flex items-center justify-between text-xs">
<span className="text-gray-500">Payment</span>
<span className="text-gray-300">{bestOffer.payment_method_name}</span>
</div>
<div className="flex items-center justify-between text-xs">
<span className="text-gray-500">Time Limit</span>
<span className="text-gray-300 flex items-center gap-1">
<Clock className="w-3 h-3" />
{bestOffer.time_limit_minutes} min
</span>
</div>
</div>
</div>
)}
{/* No Offers Warning */}
{!bestOffer && parseFloat(amount) > 0 && !isLoading && (
<div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-red-400" />
<span className="text-sm text-red-400">
No offers available for this pair
</span>
</div>
)}
{/* Express Trade Button */}
<Button
className="w-full bg-yellow-500 hover:bg-yellow-600 text-black font-semibold"
size="lg"
onClick={handleExpressTrade}
disabled={!bestOffer || isLoading || isProcessing || !user}
>
{isProcessing ? (
<>Processing...</>
) : (
<>
<Zap className="w-4 h-4 mr-2" />
{mode === 'buy' ? 'Buy' : 'Sell'} {token} Instantly
</>
)}
</Button>
{/* Trust Indicators */}
<div className="flex items-center justify-center gap-4 text-xs text-gray-500">
<span className="flex items-center gap-1">
<Shield className="w-3 h-3 text-green-400" />
Escrow Protected
</span>
<span className="flex items-center gap-1">
<CheckCircle2 className="w-3 h-3 text-blue-400" />
Verified Merchants
</span>
</div>
</CardContent>
</Card>
);
}
+176
View File
@@ -0,0 +1,176 @@
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import {
Wallet,
ArrowDownToLine,
ArrowUpFromLine,
RefreshCw,
Lock,
Unlock
} from 'lucide-react';
import { getInternalBalances, type InternalBalance } from '@shared/lib/p2p-fiat';
interface InternalBalanceCardProps {
onDeposit?: () => void;
onWithdraw?: () => void;
}
export function InternalBalanceCard({ onDeposit, onWithdraw }: InternalBalanceCardProps) {
const [balances, setBalances] = useState<InternalBalance[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const fetchBalances = async () => {
try {
const data = await getInternalBalances();
setBalances(data);
} catch (error) {
console.error('Failed to fetch balances:', error);
} finally {
setIsLoading(false);
setIsRefreshing(false);
}
};
useEffect(() => {
fetchBalances();
}, []);
const handleRefresh = async () => {
setIsRefreshing(true);
await fetchBalances();
};
const formatBalance = (value: number, decimals: number = 4) => {
return value.toLocaleString(undefined, {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
});
};
if (isLoading) {
return (
<Card>
<CardHeader className="pb-2">
<Skeleton className="h-6 w-32" />
</CardHeader>
<CardContent>
<div className="space-y-4">
<Skeleton className="h-16 w-full" />
<Skeleton className="h-16 w-full" />
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2 text-lg">
<Wallet className="h-5 w-5" />
P2P Internal Balance
</CardTitle>
<Button
variant="ghost"
size="icon"
onClick={handleRefresh}
disabled={isRefreshing}
>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Internal balance for P2P trading. Deposit to start selling.
</p>
</CardHeader>
<CardContent className="space-y-4">
{balances.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<Wallet className="h-12 w-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">No balance yet</p>
<p className="text-xs">Deposit crypto to start P2P trading</p>
</div>
) : (
balances.map((balance) => (
<div
key={balance.token}
className="p-4 rounded-lg bg-muted/50 border"
>
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
<span className="text-xs font-bold text-primary">
{balance.token.charAt(0)}
</span>
</div>
<span className="font-semibold">{balance.token}</span>
</div>
<Badge variant="outline" className="text-xs">
Total: {formatBalance(balance.total_balance)}
</Badge>
</div>
<div className="grid grid-cols-2 gap-4 text-sm">
<div className="flex items-center gap-2">
<Unlock className="h-4 w-4 text-green-500" />
<div>
<p className="text-muted-foreground text-xs">Available</p>
<p className="font-medium text-green-600">
{formatBalance(balance.available_balance)}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Lock className="h-4 w-4 text-yellow-500" />
<div>
<p className="text-muted-foreground text-xs">Locked (Escrow)</p>
<p className="font-medium text-yellow-600">
{formatBalance(balance.locked_balance)}
</p>
</div>
</div>
</div>
<div className="mt-3 pt-3 border-t grid grid-cols-2 gap-2 text-xs text-muted-foreground">
<div>
<span>Total Deposited: </span>
<span className="text-foreground">{formatBalance(balance.total_deposited, 2)}</span>
</div>
<div>
<span>Total Withdrawn: </span>
<span className="text-foreground">{formatBalance(balance.total_withdrawn, 2)}</span>
</div>
</div>
</div>
))
)}
{/* Action Buttons */}
<div className="flex gap-2">
<Button
variant="default"
className="flex-1"
onClick={onDeposit}
>
<ArrowDownToLine className="h-4 w-4 mr-2" />
Deposit
</Button>
<Button
variant="outline"
className="flex-1"
onClick={onWithdraw}
disabled={balances.every(b => b.available_balance <= 0)}
>
<ArrowUpFromLine className="h-4 w-4 mr-2" />
Withdraw
</Button>
</div>
</CardContent>
</Card>
);
}
+506
View File
@@ -0,0 +1,506 @@
import { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { toast } from 'sonner';
import { MerchantTierBadge, type MerchantTier } from './MerchantTierBadge';
import {
ArrowRight,
Check,
CheckCircle2,
Clock,
Crown,
Diamond,
Info,
Loader2,
Lock,
Shield,
Star,
TrendingUp
} from 'lucide-react';
// Tier requirements interface
interface TierRequirements {
tier: MerchantTier;
min_trades: number;
min_completion_rate: number;
min_volume_30d: number;
deposit_required: number;
deposit_token: string;
max_pending_orders: number;
max_order_amount: number;
featured_ads_allowed: number;
description: string;
}
// User stats interface
interface UserStats {
completed_trades: number;
completion_rate: number;
volume_30d: number;
}
// Current tier info
interface CurrentTierInfo {
tier: MerchantTier;
application_status: string | null;
applied_for_tier: string | null;
}
// Default tier requirements
const DEFAULT_REQUIREMENTS: TierRequirements[] = [
{
tier: 'lite',
min_trades: 0,
min_completion_rate: 0,
min_volume_30d: 0,
deposit_required: 0,
deposit_token: 'HEZ',
max_pending_orders: 5,
max_order_amount: 10000,
featured_ads_allowed: 0,
description: 'Basic tier for all verified users'
},
{
tier: 'super',
min_trades: 20,
min_completion_rate: 90,
min_volume_30d: 5000,
deposit_required: 10000,
deposit_token: 'HEZ',
max_pending_orders: 20,
max_order_amount: 100000,
featured_ads_allowed: 3,
description: 'Professional trader tier with higher limits'
},
{
tier: 'diamond',
min_trades: 100,
min_completion_rate: 95,
min_volume_30d: 25000,
deposit_required: 50000,
deposit_token: 'HEZ',
max_pending_orders: 50,
max_order_amount: 150000,
featured_ads_allowed: 10,
description: 'Elite merchant tier with maximum privileges'
}
];
// Tier icon mapping
const TIER_ICONS = {
lite: Shield,
super: Star,
diamond: Diamond
};
// Tier colors
const TIER_COLORS = {
lite: 'text-gray-400',
super: 'text-yellow-500',
diamond: 'text-purple-500'
};
export function MerchantApplication() {
const [loading, setLoading] = useState(true);
const [requirements, setRequirements] = useState<TierRequirements[]>(DEFAULT_REQUIREMENTS);
const [userStats, setUserStats] = useState<UserStats>({ completed_trades: 0, completion_rate: 0, volume_30d: 0 });
const [currentTier, setCurrentTier] = useState<CurrentTierInfo>({ tier: 'lite', application_status: null, applied_for_tier: null });
const [applyModalOpen, setApplyModalOpen] = useState(false);
const [selectedTier, setSelectedTier] = useState<MerchantTier | null>(null);
const [applying, setApplying] = useState(false);
// Fetch data
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
setLoading(true);
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) return;
// Fetch tier requirements
const { data: reqData } = await supabase
.from('p2p_tier_requirements')
.select('*')
.order('min_trades', { ascending: true });
if (reqData && reqData.length > 0) {
setRequirements(reqData as TierRequirements[]);
}
// Fetch user reputation
const { data: repData } = await supabase
.from('p2p_reputation')
.select('completed_trades')
.eq('user_id', user.id)
.single();
// Fetch merchant stats
const { data: statsData } = await supabase
.from('p2p_merchant_stats')
.select('completion_rate_30d, total_volume_30d')
.eq('user_id', user.id)
.single();
// Fetch current tier
const { data: tierData } = await supabase
.from('p2p_merchant_tiers')
.select('tier, application_status, applied_for_tier')
.eq('user_id', user.id)
.single();
setUserStats({
completed_trades: repData?.completed_trades || 0,
completion_rate: statsData?.completion_rate_30d || 0,
volume_30d: statsData?.total_volume_30d || 0
});
if (tierData) {
setCurrentTier(tierData as CurrentTierInfo);
}
} catch (error) {
console.error('Error fetching merchant data:', error);
} finally {
setLoading(false);
}
};
// Calculate progress for a requirement
const calculateProgress = (current: number, required: number): number => {
if (required === 0) return 100;
return Math.min((current / required) * 100, 100);
};
// Check if tier is unlocked
const isTierUnlocked = (tier: TierRequirements): boolean => {
return (
userStats.completed_trades >= tier.min_trades &&
userStats.completion_rate >= tier.min_completion_rate &&
userStats.volume_30d >= tier.min_volume_30d
);
};
// Get tier index for comparison
const getTierIndex = (tier: MerchantTier): number => {
return requirements.findIndex(r => r.tier === tier);
};
// Check if can apply for tier
const canApplyForTier = (tier: TierRequirements): boolean => {
if (!isTierUnlocked(tier)) return false;
if (getTierIndex(currentTier.tier) >= getTierIndex(tier.tier)) return false;
if (currentTier.application_status === 'pending') return false;
return true;
};
// Apply for tier
const applyForTier = async () => {
if (!selectedTier) return;
setApplying(true);
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error('Not authenticated');
const { data, error } = await supabase.rpc('apply_for_tier_upgrade', {
p_user_id: user.id,
p_target_tier: selectedTier
});
if (error) throw error;
if (data && data[0]) {
if (data[0].success) {
toast.success('Application submitted successfully!');
setApplyModalOpen(false);
fetchData();
} else {
toast.error(data[0].message || 'Application failed');
}
}
} catch (error) {
console.error('Error applying for tier:', error);
toast.error('Failed to submit application');
} finally {
setApplying(false);
}
};
// Open apply modal
const openApplyModal = (tier: MerchantTier) => {
setSelectedTier(tier);
setApplyModalOpen(true);
};
if (loading) {
return (
<Card>
<CardContent className="py-12 flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</CardContent>
</Card>
);
}
return (
<div className="space-y-6">
{/* Current Tier Card */}
<Card className="bg-gradient-to-br from-kurdish-green/10 to-transparent border-kurdish-green/30">
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="flex items-center gap-2">
<Crown className="h-5 w-5 text-kurdish-green" />
Your Merchant Status
</CardTitle>
<CardDescription>Current tier and application status</CardDescription>
</div>
<MerchantTierBadge tier={currentTier.tier} size="lg" />
</div>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-4">
<div className="text-center p-4 bg-background/50 rounded-lg">
<p className="text-2xl font-bold">{userStats.completed_trades}</p>
<p className="text-sm text-muted-foreground">Completed Trades</p>
</div>
<div className="text-center p-4 bg-background/50 rounded-lg">
<p className="text-2xl font-bold">{userStats.completion_rate.toFixed(1)}%</p>
<p className="text-sm text-muted-foreground">Completion Rate</p>
</div>
<div className="text-center p-4 bg-background/50 rounded-lg">
<p className="text-2xl font-bold">${userStats.volume_30d.toLocaleString()}</p>
<p className="text-sm text-muted-foreground">30-Day Volume</p>
</div>
</div>
{currentTier.application_status === 'pending' && (
<Alert className="mt-4 bg-yellow-500/10 border-yellow-500/30">
<Clock className="h-4 w-4 text-yellow-500" />
<AlertDescription className="text-yellow-500">
Your application for {currentTier.applied_for_tier?.toUpperCase()} tier is pending review.
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
{/* Tier Progression */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{requirements.map((tier) => {
const TierIcon = TIER_ICONS[tier.tier];
const isCurrentTier = tier.tier === currentTier.tier;
const isUnlocked = isTierUnlocked(tier);
const canApply = canApplyForTier(tier);
const isPastTier = getTierIndex(tier.tier) < getTierIndex(currentTier.tier);
return (
<Card
key={tier.tier}
className={`relative overflow-hidden transition-all ${
isCurrentTier
? 'border-kurdish-green bg-kurdish-green/5'
: isPastTier
? 'border-green-500/30 bg-green-500/5'
: isUnlocked
? 'border-yellow-500/30 hover:border-yellow-500/50'
: 'opacity-75'
}`}
>
{/* Current tier indicator */}
{isCurrentTier && (
<div className="absolute top-0 right-0 bg-kurdish-green text-white text-xs px-2 py-0.5 rounded-bl">
Current
</div>
)}
{isPastTier && (
<div className="absolute top-0 right-0 bg-green-500 text-white text-xs px-2 py-0.5 rounded-bl">
<Check className="h-3 w-3" />
</div>
)}
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className={`p-2 rounded-full bg-background ${TIER_COLORS[tier.tier]}`}>
<TierIcon className="h-5 w-5" />
</div>
<div>
<CardTitle className="text-lg capitalize">{tier.tier}</CardTitle>
<CardDescription className="text-xs">{tier.description}</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Requirements */}
<div className="space-y-3">
{/* Trades */}
<div>
<div className="flex justify-between text-xs mb-1">
<span>Completed Trades</span>
<span>{userStats.completed_trades} / {tier.min_trades}</span>
</div>
<Progress
value={calculateProgress(userStats.completed_trades, tier.min_trades)}
className="h-1.5"
/>
</div>
{/* Completion Rate */}
{tier.min_completion_rate > 0 && (
<div>
<div className="flex justify-between text-xs mb-1">
<span>Completion Rate</span>
<span>{userStats.completion_rate.toFixed(1)}% / {tier.min_completion_rate}%</span>
</div>
<Progress
value={calculateProgress(userStats.completion_rate, tier.min_completion_rate)}
className="h-1.5"
/>
</div>
)}
{/* Volume */}
{tier.min_volume_30d > 0 && (
<div>
<div className="flex justify-between text-xs mb-1">
<span>30-Day Volume</span>
<span>${userStats.volume_30d.toLocaleString()} / ${tier.min_volume_30d.toLocaleString()}</span>
</div>
<Progress
value={calculateProgress(userStats.volume_30d, tier.min_volume_30d)}
className="h-1.5"
/>
</div>
)}
</div>
{/* Benefits */}
<div className="pt-2 border-t border-border/50">
<p className="text-xs text-muted-foreground mb-2">Benefits:</p>
<div className="space-y-1 text-xs">
<div className="flex items-center gap-1">
<CheckCircle2 className="h-3 w-3 text-kurdish-green" />
<span>Up to {tier.max_pending_orders} pending orders</span>
</div>
<div className="flex items-center gap-1">
<CheckCircle2 className="h-3 w-3 text-kurdish-green" />
<span>Max ${tier.max_order_amount.toLocaleString()} per trade</span>
</div>
{tier.featured_ads_allowed > 0 && (
<div className="flex items-center gap-1">
<CheckCircle2 className="h-3 w-3 text-kurdish-green" />
<span>{tier.featured_ads_allowed} featured ads</span>
</div>
)}
</div>
</div>
{/* Deposit requirement */}
{tier.deposit_required > 0 && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Lock className="h-3 w-3" />
<span>Requires {tier.deposit_required.toLocaleString()} {tier.deposit_token} deposit</span>
</div>
)}
{/* Action button */}
{canApply && (
<Button
className="w-full mt-2 bg-kurdish-green hover:bg-kurdish-green-dark"
size="sm"
onClick={() => openApplyModal(tier.tier)}
>
Apply for Upgrade
<ArrowRight className="h-4 w-4 ml-1" />
</Button>
)}
</CardContent>
</Card>
);
})}
</div>
{/* Apply Modal */}
<Dialog open={applyModalOpen} onOpenChange={setApplyModalOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<TrendingUp className="h-5 w-5 text-kurdish-green" />
Apply for {selectedTier?.toUpperCase()} Tier
</DialogTitle>
<DialogDescription>
Submit your application for tier upgrade. Our team will review it shortly.
</DialogDescription>
</DialogHeader>
{selectedTier && (
<div className="space-y-4">
{/* Requirements check */}
<div className="bg-muted p-4 rounded-lg space-y-2">
<p className="font-medium text-sm">Requirements Met:</p>
{requirements.find(r => r.tier === selectedTier) && (
<>
<div className="flex items-center gap-2 text-sm">
<CheckCircle2 className="h-4 w-4 text-green-500" />
<span>Completed trades requirement</span>
</div>
<div className="flex items-center gap-2 text-sm">
<CheckCircle2 className="h-4 w-4 text-green-500" />
<span>Completion rate requirement</span>
</div>
<div className="flex items-center gap-2 text-sm">
<CheckCircle2 className="h-4 w-4 text-green-500" />
<span>30-day volume requirement</span>
</div>
</>
)}
</div>
{/* Deposit info */}
{(requirements.find(r => r.tier === selectedTier)?.deposit_required ?? 0) > 0 && (
<Alert>
<Info className="h-4 w-4" />
<AlertDescription>
This tier requires a deposit of{' '}
<strong>
{requirements.find(r => r.tier === selectedTier)?.deposit_required.toLocaleString()}{' '}
{requirements.find(r => r.tier === selectedTier)?.deposit_token}
</strong>
. You will be prompted to complete the deposit after approval.
</AlertDescription>
</Alert>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setApplyModalOpen(false)}>
Cancel
</Button>
<Button
className="bg-kurdish-green hover:bg-kurdish-green-dark"
onClick={applyForTier}
disabled={applying}
>
{applying ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Check className="h-4 w-4 mr-2" />
)}
Submit Application
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
export default MerchantApplication;
+110
View File
@@ -0,0 +1,110 @@
import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Diamond, Star, Shield } from 'lucide-react';
export type MerchantTier = 'lite' | 'super' | 'diamond';
interface MerchantTierBadgeProps {
tier: MerchantTier;
size?: 'sm' | 'md' | 'lg';
showLabel?: boolean;
}
const TIER_CONFIG = {
lite: {
label: 'Lite',
icon: Shield,
className: 'bg-gray-500/20 text-gray-400 border-gray-500/30',
iconClassName: 'text-gray-400',
description: 'Basic verified trader'
},
super: {
label: 'Super',
icon: Star,
className: 'bg-yellow-500/20 text-yellow-500 border-yellow-500/30',
iconClassName: 'text-yellow-500',
description: 'Professional trader with 20+ trades and 90%+ completion rate'
},
diamond: {
label: 'Diamond',
icon: Diamond,
className: 'bg-purple-500/20 text-purple-500 border-purple-500/30',
iconClassName: 'text-purple-500',
description: 'Elite merchant with 100+ trades and 95%+ completion rate'
}
};
const SIZE_CONFIG = {
sm: {
badge: 'text-[10px] px-1.5 py-0.5',
icon: 'h-3 w-3'
},
md: {
badge: 'text-xs px-2 py-1',
icon: 'h-3.5 w-3.5'
},
lg: {
badge: 'text-sm px-3 py-1.5',
icon: 'h-4 w-4'
}
};
export function MerchantTierBadge({
tier,
size = 'md',
showLabel = true
}: MerchantTierBadgeProps) {
const config = TIER_CONFIG[tier];
const sizeConfig = SIZE_CONFIG[size];
const Icon = config.icon;
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Badge
variant="outline"
className={`${config.className} ${sizeConfig.badge} gap-1 cursor-help`}
>
<Icon className={`${sizeConfig.icon} ${config.iconClassName}`} />
{showLabel && <span>{config.label}</span>}
</Badge>
</TooltipTrigger>
<TooltipContent>
<p className="font-medium">{config.label} Merchant</p>
<p className="text-xs text-muted-foreground">{config.description}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
// Standalone tier icon for compact displays
export function MerchantTierIcon({
tier,
size = 'md'
}: {
tier: MerchantTier;
size?: 'sm' | 'md' | 'lg';
}) {
const config = TIER_CONFIG[tier];
const sizeConfig = SIZE_CONFIG[size];
const Icon = config.icon;
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-help">
<Icon className={`${sizeConfig.icon} ${config.iconClassName}`} />
</span>
</TooltipTrigger>
<TooltipContent>
<p className="font-medium">{config.label} Merchant</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
export default MerchantTierBadge;
+284
View File
@@ -0,0 +1,284 @@
import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
Bell,
MessageSquare,
DollarSign,
CheckCircle2,
XCircle,
AlertTriangle,
Star,
Loader2,
CheckCheck,
} from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/lib/supabase';
interface Notification {
id: string;
user_id: string;
type: string;
title: string;
message: string;
reference_type?: string;
reference_id?: string;
is_read: boolean;
created_at: string;
}
export function NotificationBell() {
const navigate = useNavigate();
const { user } = useAuth();
const [notifications, setNotifications] = useState<Notification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const [loading, setLoading] = useState(true);
const [isOpen, setIsOpen] = useState(false);
// Fetch notifications
const fetchNotifications = useCallback(async () => {
if (!user) return;
try {
const { data, error } = await supabase
.from('p2p_notifications')
.select('*')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
.limit(20);
if (error) throw error;
setNotifications(data || []);
setUnreadCount(data?.filter(n => !n.is_read).length || 0);
} catch (error) {
console.error('Fetch notifications error:', error);
} finally {
setLoading(false);
}
}, [user]);
// Initial fetch
useEffect(() => {
fetchNotifications();
}, [fetchNotifications]);
// Real-time subscription
useEffect(() => {
if (!user) return;
const channel = supabase
.channel(`notifications-${user.id}`)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'p2p_notifications',
filter: `user_id=eq.${user.id}`,
},
(payload) => {
const newNotif = payload.new as Notification;
setNotifications(prev => [newNotif, ...prev.slice(0, 19)]);
setUnreadCount(prev => prev + 1);
}
)
.subscribe();
return () => {
supabase.removeChannel(channel);
};
}, [user]);
// Mark as read
const markAsRead = async (notificationId: string) => {
try {
await supabase
.from('p2p_notifications')
.update({ is_read: true })
.eq('id', notificationId);
setNotifications(prev =>
prev.map(n => n.id === notificationId ? { ...n, is_read: true } : n)
);
setUnreadCount(prev => Math.max(0, prev - 1));
} catch (error) {
console.error('Mark as read error:', error);
}
};
// Mark all as read
const markAllAsRead = async () => {
if (!user) return;
try {
await supabase
.from('p2p_notifications')
.update({ is_read: true })
.eq('user_id', user.id)
.eq('is_read', false);
setNotifications(prev => prev.map(n => ({ ...n, is_read: true })));
setUnreadCount(0);
} catch (error) {
console.error('Mark all as read error:', error);
}
};
// Handle notification click
const handleClick = (notification: Notification) => {
// Mark as read
if (!notification.is_read) {
markAsRead(notification.id);
}
// Navigate to reference
if (notification.reference_type === 'trade' && notification.reference_id) {
navigate(`/p2p/trade/${notification.reference_id}`);
setIsOpen(false);
}
};
// Get icon for notification type
const getIcon = (type: string) => {
switch (type) {
case 'new_message':
return <MessageSquare className="w-4 h-4 text-blue-400" />;
case 'payment_sent':
return <DollarSign className="w-4 h-4 text-yellow-400" />;
case 'payment_confirmed':
return <CheckCircle2 className="w-4 h-4 text-green-400" />;
case 'trade_cancelled':
return <XCircle className="w-4 h-4 text-gray-400" />;
case 'dispute_opened':
return <AlertTriangle className="w-4 h-4 text-red-400" />;
case 'new_rating':
return <Star className="w-4 h-4 text-yellow-400" />;
case 'new_order':
return <DollarSign className="w-4 h-4 text-green-400" />;
default:
return <Bell className="w-4 h-4 text-gray-400" />;
}
};
// Format time ago
const formatTimeAgo = (dateString: string) => {
const seconds = Math.floor((Date.now() - new Date(dateString).getTime()) / 1000);
if (seconds < 60) return 'Just now';
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
};
if (!user) return null;
return (
<DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="relative text-gray-400 hover:text-white"
>
<Bell className="w-5 h-5" />
{unreadCount > 0 && (
<span className="absolute -top-1 -right-1 w-5 h-5 flex items-center justify-center bg-red-500 text-white text-xs rounded-full">
{unreadCount > 9 ? '9+' : unreadCount}
</span>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="w-80 bg-gray-900 border-gray-800"
>
<DropdownMenuLabel className="flex items-center justify-between">
<span className="text-white">Notifications</span>
{unreadCount > 0 && (
<Button
variant="ghost"
size="sm"
onClick={markAllAsRead}
className="text-xs text-gray-400 hover:text-white h-auto py-1"
>
<CheckCheck className="w-3 h-3 mr-1" />
Mark all read
</Button>
)}
</DropdownMenuLabel>
<DropdownMenuSeparator className="bg-gray-800" />
<ScrollArea className="h-[300px]">
{loading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-gray-500" />
</div>
) : notifications.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-gray-500">
<Bell className="w-8 h-8 mb-2" />
<p className="text-sm">No notifications</p>
</div>
) : (
notifications.map((notification) => (
<DropdownMenuItem
key={notification.id}
onClick={() => handleClick(notification)}
className={`
flex items-start gap-3 p-3 cursor-pointer
${!notification.is_read ? 'bg-gray-800/50' : ''}
hover:bg-gray-800
`}
>
<div className="mt-0.5">{getIcon(notification.type)}</div>
<div className="flex-1 min-w-0">
<p className={`text-sm ${!notification.is_read ? 'text-white font-medium' : 'text-gray-300'}`}>
{notification.title}
</p>
{notification.message && (
<p className="text-xs text-gray-500 truncate">
{notification.message}
</p>
)}
<p className="text-xs text-gray-600 mt-1">
{formatTimeAgo(notification.created_at)}
</p>
</div>
{!notification.is_read && (
<div className="w-2 h-2 bg-blue-500 rounded-full mt-1.5" />
)}
</DropdownMenuItem>
))
)}
</ScrollArea>
{notifications.length > 0 && (
<>
<DropdownMenuSeparator className="bg-gray-800" />
<DropdownMenuItem
onClick={() => {
navigate('/p2p/orders');
setIsOpen(false);
}}
className="justify-center text-gray-400 hover:text-white cursor-pointer"
>
View all trades
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
+490
View File
@@ -0,0 +1,490 @@
import { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Slider } from '@/components/ui/slider';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger, SheetFooter } from '@/components/ui/sheet';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import {
ChevronDown,
Filter,
RefreshCw,
SlidersHorizontal,
Star,
Diamond,
X,
Check
} from 'lucide-react';
// Import types from separate file to avoid react-refresh warning
import { type P2PFilters, DEFAULT_FILTERS } from './types';
// Available fiat currencies
const FIAT_CURRENCIES = [
{ value: 'TRY', label: 'TRY - Turkish Lira' },
{ value: 'EUR', label: 'EUR - Euro' },
{ value: 'USD', label: 'USD - US Dollar' },
{ value: 'IQD', label: 'IQD - Iraqi Dinar' },
{ value: 'IRR', label: 'IRR - Iranian Rial' }
];
// Merchant tiers
const MERCHANT_TIERS = [
{ value: 'super', label: 'Super', icon: Star, color: 'text-yellow-500' },
{ value: 'diamond', label: 'Diamond', icon: Diamond, color: 'text-purple-500' }
];
interface OrderFiltersProps {
filters: P2PFilters;
onFiltersChange: (filters: P2PFilters) => void;
variant?: 'inline' | 'sheet';
}
export function OrderFilters({
filters,
onFiltersChange,
variant = 'inline'
}: OrderFiltersProps) {
const [localFilters, setLocalFilters] = useState<P2PFilters>(filters);
const [paymentMethods, setPaymentMethods] = useState<{ id: string; method_name: string }[]>([]);
const [isOpen, setIsOpen] = useState(false);
const [expandedSections, setExpandedSections] = useState({
currency: true,
payment: false,
merchant: false,
amount: false
});
// Fetch payment methods
useEffect(() => {
const fetchPaymentMethods = async () => {
const { data } = await supabase
.from('payment_methods')
.select('id, method_name')
.eq('is_active', true);
if (data) {
setPaymentMethods(data);
}
};
fetchPaymentMethods();
}, []);
// Update local filters
const updateFilter = <K extends keyof P2PFilters>(key: K, value: P2PFilters[K]) => {
setLocalFilters(prev => ({ ...prev, [key]: value }));
};
// Apply filters
const applyFilters = () => {
onFiltersChange(localFilters);
setIsOpen(false);
};
// Reset filters
const resetFilters = () => {
setLocalFilters(DEFAULT_FILTERS);
onFiltersChange(DEFAULT_FILTERS);
};
// Toggle section
const toggleSection = (section: keyof typeof expandedSections) => {
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
};
// Count active filters
const activeFilterCount = () => {
let count = 0;
if (localFilters.token !== 'all') count++;
if (localFilters.fiatCurrency !== 'all') count++;
if (localFilters.paymentMethods.length > 0) count++;
if (localFilters.minAmount !== null || localFilters.maxAmount !== null) count++;
if (localFilters.merchantTiers.length > 0) count++;
if (localFilters.minCompletionRate > 0) count++;
if (localFilters.onlineOnly) count++;
if (localFilters.verifiedOnly) count++;
return count;
};
// Filter content
const FilterContent = () => (
<div className="space-y-4">
{/* Token Selection */}
<div className="space-y-2">
<Label>Cryptocurrency</Label>
<div className="flex gap-2">
{['all', 'HEZ', 'PEZ'].map((token) => (
<Button
key={token}
variant={localFilters.token === token ? 'default' : 'outline'}
size="sm"
onClick={() => updateFilter('token', token as P2PFilters['token'])}
className={localFilters.token === token ? 'bg-kurdish-green hover:bg-kurdish-green-dark' : ''}
>
{token === 'all' ? 'All' : token}
</Button>
))}
</div>
</div>
{/* Fiat Currency */}
<Collapsible open={expandedSections.currency} onOpenChange={() => toggleSection('currency')}>
<CollapsibleTrigger className="flex items-center justify-between w-full py-2">
<Label className="cursor-pointer">Fiat Currency</Label>
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.currency ? 'rotate-180' : ''}`} />
</CollapsibleTrigger>
<CollapsibleContent className="pt-2">
<Select
value={localFilters.fiatCurrency}
onValueChange={(value) => updateFilter('fiatCurrency', value)}
>
<SelectTrigger>
<SelectValue placeholder="Select currency" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Currencies</SelectItem>
{FIAT_CURRENCIES.map((currency) => (
<SelectItem key={currency.value} value={currency.value}>
{currency.label}
</SelectItem>
))}
</SelectContent>
</Select>
</CollapsibleContent>
</Collapsible>
{/* Payment Methods */}
<Collapsible open={expandedSections.payment} onOpenChange={() => toggleSection('payment')}>
<CollapsibleTrigger className="flex items-center justify-between w-full py-2">
<Label className="cursor-pointer">Payment Methods</Label>
<div className="flex items-center gap-2">
{localFilters.paymentMethods.length > 0 && (
<Badge variant="secondary" className="text-xs">
{localFilters.paymentMethods.length}
</Badge>
)}
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.payment ? 'rotate-180' : ''}`} />
</div>
</CollapsibleTrigger>
<CollapsibleContent className="pt-2 space-y-2">
{paymentMethods.map((method) => (
<div key={method.id} className="flex items-center space-x-2">
<Checkbox
id={method.id}
checked={localFilters.paymentMethods.includes(method.id)}
onCheckedChange={(checked) => {
if (checked) {
updateFilter('paymentMethods', [...localFilters.paymentMethods, method.id]);
} else {
updateFilter('paymentMethods', localFilters.paymentMethods.filter(id => id !== method.id));
}
}}
/>
<label htmlFor={method.id} className="text-sm cursor-pointer">
{method.method_name}
</label>
</div>
))}
</CollapsibleContent>
</Collapsible>
{/* Amount Range */}
<Collapsible open={expandedSections.amount} onOpenChange={() => toggleSection('amount')}>
<CollapsibleTrigger className="flex items-center justify-between w-full py-2">
<Label className="cursor-pointer">Amount Range</Label>
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.amount ? 'rotate-180' : ''}`} />
</CollapsibleTrigger>
<CollapsibleContent className="pt-2">
<div className="grid grid-cols-2 gap-2">
<div>
<Label className="text-xs">Min Amount</Label>
<Input
type="number"
placeholder="0"
value={localFilters.minAmount || ''}
onChange={(e) => updateFilter('minAmount', e.target.value ? Number(e.target.value) : null)}
/>
</div>
<div>
<Label className="text-xs">Max Amount</Label>
<Input
type="number"
placeholder="No limit"
value={localFilters.maxAmount || ''}
onChange={(e) => updateFilter('maxAmount', e.target.value ? Number(e.target.value) : null)}
/>
</div>
</div>
</CollapsibleContent>
</Collapsible>
{/* Merchant Tier */}
<Collapsible open={expandedSections.merchant} onOpenChange={() => toggleSection('merchant')}>
<CollapsibleTrigger className="flex items-center justify-between w-full py-2">
<Label className="cursor-pointer">Merchant Tier</Label>
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.merchant ? 'rotate-180' : ''}`} />
</CollapsibleTrigger>
<CollapsibleContent className="pt-2 space-y-2">
{MERCHANT_TIERS.map((tier) => {
const Icon = tier.icon;
return (
<div key={tier.value} className="flex items-center space-x-2">
<Checkbox
id={`tier-${tier.value}`}
checked={localFilters.merchantTiers.includes(tier.value as 'super' | 'diamond')}
onCheckedChange={(checked) => {
if (checked) {
updateFilter('merchantTiers', [...localFilters.merchantTiers, tier.value as 'super' | 'diamond']);
} else {
updateFilter('merchantTiers', localFilters.merchantTiers.filter(t => t !== tier.value));
}
}}
/>
<label htmlFor={`tier-${tier.value}`} className="flex items-center gap-1 text-sm cursor-pointer">
<Icon className={`h-4 w-4 ${tier.color}`} />
{tier.label}+ only
</label>
</div>
);
})}
</CollapsibleContent>
</Collapsible>
{/* Completion Rate */}
<div className="space-y-2">
<Label>Min Completion Rate: {localFilters.minCompletionRate}%</Label>
<Slider
value={[localFilters.minCompletionRate]}
onValueChange={([value]) => updateFilter('minCompletionRate', value)}
max={100}
step={5}
className="py-2"
/>
</div>
{/* Toggle options */}
<div className="space-y-2">
<div className="flex items-center space-x-2">
<Checkbox
id="online-only"
checked={localFilters.onlineOnly}
onCheckedChange={(checked) => updateFilter('onlineOnly', !!checked)}
/>
<label htmlFor="online-only" className="text-sm cursor-pointer">
Online traders only
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="verified-only"
checked={localFilters.verifiedOnly}
onCheckedChange={(checked) => updateFilter('verifiedOnly', !!checked)}
/>
<label htmlFor="verified-only" className="text-sm cursor-pointer">
Verified merchants only
</label>
</div>
</div>
{/* Sort */}
<div className="space-y-2">
<Label>Sort By</Label>
<div className="grid grid-cols-2 gap-2">
<Select
value={localFilters.sortBy}
onValueChange={(value) => updateFilter('sortBy', value as P2PFilters['sortBy'])}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="price">Price</SelectItem>
<SelectItem value="completion_rate">Completion Rate</SelectItem>
<SelectItem value="trades">Trade Count</SelectItem>
<SelectItem value="newest">Newest</SelectItem>
</SelectContent>
</Select>
<Select
value={localFilters.sortOrder}
onValueChange={(value) => updateFilter('sortOrder', value as 'asc' | 'desc')}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="asc">Low to High</SelectItem>
<SelectItem value="desc">High to Low</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
);
// Sheet variant (mobile)
if (variant === 'sheet') {
return (
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<SlidersHorizontal className="h-4 w-4" />
Filters
{activeFilterCount() > 0 && (
<Badge variant="secondary" className="ml-1">
{activeFilterCount()}
</Badge>
)}
</Button>
</SheetTrigger>
<SheetContent side="right" className="w-full sm:max-w-md">
<SheetHeader>
<SheetTitle className="flex items-center justify-between">
<span className="flex items-center gap-2">
<Filter className="h-5 w-5" />
Filter Orders
</span>
<Button variant="ghost" size="sm" onClick={resetFilters}>
<RefreshCw className="h-4 w-4 mr-1" />
Reset
</Button>
</SheetTitle>
</SheetHeader>
<div className="py-4 overflow-y-auto max-h-[calc(100vh-200px)]">
<FilterContent />
</div>
<SheetFooter className="absolute bottom-0 left-0 right-0 p-4 bg-background border-t">
<Button variant="outline" onClick={() => setIsOpen(false)} className="flex-1">
Cancel
</Button>
<Button onClick={applyFilters} className="flex-1 bg-kurdish-green hover:bg-kurdish-green-dark">
<Check className="h-4 w-4 mr-1" />
Apply Filters
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}
// Inline variant (desktop)
return (
<Card>
<CardContent className="pt-4">
<div className="flex items-center justify-between mb-4">
<h3 className="font-medium flex items-center gap-2">
<Filter className="h-4 w-4" />
Filters
</h3>
<Button variant="ghost" size="sm" onClick={resetFilters}>
<RefreshCw className="h-4 w-4 mr-1" />
Reset
</Button>
</div>
<FilterContent />
<Button onClick={applyFilters} className="w-full mt-4 bg-kurdish-green hover:bg-kurdish-green-dark">
<Check className="h-4 w-4 mr-1" />
Apply Filters
</Button>
</CardContent>
</Card>
);
}
// Quick filter bar for top of listing
export function QuickFilterBar({
filters,
onFiltersChange
}: {
filters: P2PFilters;
onFiltersChange: (filters: P2PFilters) => void;
}) {
return (
<div className="flex flex-wrap items-center gap-2">
{/* Token quick select */}
<div className="flex gap-1">
{['all', 'HEZ', 'PEZ'].map((token) => (
<Button
key={token}
variant={filters.token === token ? 'default' : 'outline'}
size="sm"
onClick={() => onFiltersChange({ ...filters, token: token as P2PFilters['token'] })}
className={filters.token === token ? 'bg-kurdish-green hover:bg-kurdish-green-dark' : ''}
>
{token === 'all' ? 'All' : token}
</Button>
))}
</div>
{/* Currency select */}
<Select
value={filters.fiatCurrency}
onValueChange={(value) => onFiltersChange({ ...filters, fiatCurrency: value })}
>
<SelectTrigger className="w-[120px] h-9">
<SelectValue placeholder="Currency" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All</SelectItem>
{FIAT_CURRENCIES.map((currency) => (
<SelectItem key={currency.value} value={currency.value}>
{currency.value}
</SelectItem>
))}
</SelectContent>
</Select>
{/* Amount input */}
<Input
type="number"
placeholder="I want to trade..."
className="w-[150px] h-9"
onChange={(e) => {
const value = e.target.value ? Number(e.target.value) : null;
onFiltersChange({ ...filters, minAmount: value, maxAmount: value ? value * 1.1 : null });
}}
/>
{/* Advanced filters sheet */}
<OrderFilters
filters={filters}
onFiltersChange={onFiltersChange}
variant="sheet"
/>
{/* Active filter badges */}
{filters.merchantTiers.length > 0 && (
<Badge variant="secondary" className="gap-1">
<Star className="h-3 w-3 text-yellow-500" />
{filters.merchantTiers.join(', ')}+
<button
onClick={() => onFiltersChange({ ...filters, merchantTiers: [] })}
className="ml-1 hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</Badge>
)}
{filters.minCompletionRate > 0 && (
<Badge variant="secondary" className="gap-1">
{filters.minCompletionRate}%+ rate
<button
onClick={() => onFiltersChange({ ...filters, minCompletionRate: 0 })}
className="ml-1 hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</Badge>
)}
</div>
);
}
export default OrderFilters;
+295
View File
@@ -0,0 +1,295 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { PlusCircle, Home, ClipboardList, TrendingUp, CheckCircle2, Clock, Store, Zap, Blocks } from 'lucide-react';
import { AdList } from './AdList';
import { CreateAd } from './CreateAd';
import { NotificationBell } from './NotificationBell';
import { QuickFilterBar } from './OrderFilters';
import { InternalBalanceCard } from './InternalBalanceCard';
import { DepositModal } from './DepositModal';
import { WithdrawModal } from './WithdrawModal';
import { ExpressMode } from './ExpressMode';
import { BlockTrade } from './BlockTrade';
import { DEFAULT_FILTERS, type P2PFilters } from './types';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/lib/supabase';
interface UserStats {
activeTrades: number;
completedTrades: number;
totalVolume: number;
}
export function P2PDashboard() {
const [showCreateAd, setShowCreateAd] = useState(false);
const [userStats, setUserStats] = useState<UserStats>({ activeTrades: 0, completedTrades: 0, totalVolume: 0 });
const [filters, setFilters] = useState<P2PFilters>(DEFAULT_FILTERS);
const [showDepositModal, setShowDepositModal] = useState(false);
const [showWithdrawModal, setShowWithdrawModal] = useState(false);
const [balanceRefreshKey, setBalanceRefreshKey] = useState(0);
const navigate = useNavigate();
const { user } = useAuth();
const handleBalanceUpdated = () => {
setBalanceRefreshKey(prev => prev + 1);
};
// Fetch user stats
useEffect(() => {
const fetchStats = async () => {
if (!user) return;
try {
// Count active trades
const { count: activeCount } = await supabase
.from('p2p_fiat_trades')
.select('*', { count: 'exact', head: true })
.or(`seller_id.eq.${user.id},buyer_id.eq.${user.id}`)
.in('status', ['pending', 'payment_sent']);
// Count completed trades
const { count: completedCount } = await supabase
.from('p2p_fiat_trades')
.select('*', { count: 'exact', head: true })
.or(`seller_id.eq.${user.id},buyer_id.eq.${user.id}`)
.eq('status', 'completed');
// Calculate total volume
const { data: trades } = await supabase
.from('p2p_fiat_trades')
.select('fiat_amount')
.or(`seller_id.eq.${user.id},buyer_id.eq.${user.id}`)
.eq('status', 'completed');
const totalVolume = trades?.reduce((sum, t) => sum + (t.fiat_amount || 0), 0) || 0;
setUserStats({
activeTrades: activeCount || 0,
completedTrades: completedCount || 0,
totalVolume,
});
} catch (error) {
console.error('Fetch stats error:', error);
}
};
fetchStats();
}, [user]);
return (
<div className="container mx-auto px-4 py-8 max-w-7xl">
<div className="flex items-center justify-between mb-4">
<Button
variant="ghost"
onClick={() => navigate('/')}
className="text-gray-400 hover:text-white"
>
<Home className="w-4 h-4 mr-2" />
Back to Home
</Button>
<div className="flex items-center gap-2">
<NotificationBell />
<Button
variant="outline"
onClick={() => navigate('/p2p/merchant')}
className="border-gray-700 hover:bg-gray-800"
>
<Store className="w-4 h-4 mr-2" />
Merchant
</Button>
<Button
variant="outline"
onClick={() => navigate('/p2p/orders')}
className="border-gray-700 hover:bg-gray-800"
>
<ClipboardList className="w-4 h-4 mr-2" />
My Trades
{userStats.activeTrades > 0 && (
<Badge className="ml-2 bg-yellow-500 text-black">
{userStats.activeTrades}
</Badge>
)}
</Button>
</div>
</div>
{/* Stats Cards and Balance Card */}
{user && (
<div className="grid grid-cols-1 lg:grid-cols-4 gap-4 mb-6">
{/* Internal Balance Card - Takes more space */}
<div className="lg:col-span-1">
<InternalBalanceCard
key={balanceRefreshKey}
onDeposit={() => setShowDepositModal(true)}
onWithdraw={() => setShowWithdrawModal(true)}
/>
</div>
{/* Stats Cards */}
<div className="lg:col-span-3 grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card className="bg-gray-900 border-gray-800">
<CardContent className="py-4 flex items-center gap-3">
<div className="p-2 bg-yellow-500/20 rounded-lg">
<Clock className="w-5 h-5 text-yellow-400" />
</div>
<div>
<p className="text-2xl font-bold text-white">{userStats.activeTrades}</p>
<p className="text-sm text-gray-400">Active Trades</p>
</div>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardContent className="py-4 flex items-center gap-3">
<div className="p-2 bg-green-500/20 rounded-lg">
<CheckCircle2 className="w-5 h-5 text-green-400" />
</div>
<div>
<p className="text-2xl font-bold text-white">{userStats.completedTrades}</p>
<p className="text-sm text-gray-400">Completed</p>
</div>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardContent className="py-4 flex items-center gap-3">
<div className="p-2 bg-blue-500/20 rounded-lg">
<TrendingUp className="w-5 h-5 text-blue-400" />
</div>
<div>
<p className="text-2xl font-bold text-white">${userStats.totalVolume.toLocaleString()}</p>
<p className="text-sm text-gray-400">Volume</p>
</div>
</CardContent>
</Card>
</div>
</div>
)}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-4xl font-bold text-white">P2P Trading</h1>
<p className="text-gray-400">Buy and sell crypto with your local currency.</p>
</div>
<Button onClick={() => setShowCreateAd(true)}>
<PlusCircle className="w-4 h-4 mr-2" />
Post a New Ad
</Button>
</div>
{showCreateAd ? (
<CreateAd onAdCreated={() => setShowCreateAd(false)} />
) : (
<>
{/* Quick Filter Bar */}
<QuickFilterBar filters={filters} onFiltersChange={setFilters} />
<Tabs defaultValue="buy">
<TabsList className="grid w-full grid-cols-5">
<TabsTrigger value="express" className="flex items-center gap-1">
<Zap className="w-3 h-3" />
Express
</TabsTrigger>
<TabsTrigger value="buy">Buy</TabsTrigger>
<TabsTrigger value="sell">Sell</TabsTrigger>
<TabsTrigger value="my-ads">My Ads</TabsTrigger>
<TabsTrigger value="otc" className="flex items-center gap-1">
<Blocks className="w-3 h-3" />
OTC
</TabsTrigger>
</TabsList>
<TabsContent value="express">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-4">
<ExpressMode onTradeStarted={(id) => navigate(`/p2p/trade/${id}`)} />
<div className="space-y-4">
<Card className="bg-gray-900 border-gray-800">
<CardContent className="pt-6">
<h3 className="text-lg font-semibold text-white mb-2">Why Express Mode?</h3>
<ul className="space-y-2 text-sm text-gray-400">
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-green-400" />
Instant best-rate matching
</li>
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-green-400" />
Verified merchants only
</li>
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-green-400" />
Escrow protection
</li>
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-green-400" />
No manual offer selection
</li>
</ul>
</CardContent>
</Card>
</div>
</div>
</TabsContent>
<TabsContent value="buy">
<AdList type="buy" filters={filters} />
</TabsContent>
<TabsContent value="sell">
<AdList type="sell" filters={filters} />
</TabsContent>
<TabsContent value="my-ads">
<AdList type="my-ads" filters={filters} />
</TabsContent>
<TabsContent value="otc">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-4">
<BlockTrade />
<div className="space-y-4">
<Card className="bg-gray-900 border-gray-800">
<CardContent className="pt-6">
<h3 className="text-lg font-semibold text-white mb-2">Block Trade Benefits</h3>
<ul className="space-y-2 text-sm text-gray-400">
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-purple-400" />
Custom pricing negotiation
</li>
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-purple-400" />
Dedicated OTC desk support
</li>
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-purple-400" />
Multi-tranche settlements
</li>
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-purple-400" />
Enhanced privacy
</li>
<li className="flex items-center gap-2">
<CheckCircle2 className="w-4 h-4 text-purple-400" />
Flexible payment terms
</li>
</ul>
</CardContent>
</Card>
</div>
</div>
</TabsContent>
</Tabs>
</>
)}
{/* Deposit Modal */}
<DepositModal
isOpen={showDepositModal}
onClose={() => setShowDepositModal(false)}
onSuccess={handleBalanceUpdated}
/>
{/* Withdraw Modal */}
<WithdrawModal
isOpen={showWithdrawModal}
onClose={() => setShowWithdrawModal(false)}
onSuccess={handleBalanceUpdated}
/>
</div>
);
}
+278
View File
@@ -0,0 +1,278 @@
import React, { useState } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Star, Loader2, ThumbsUp, ThumbsDown } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';
import { supabase } from '@/lib/supabase';
interface RatingModalProps {
isOpen: boolean;
onClose: () => void;
tradeId: string;
counterpartyId: string;
counterpartyWallet: string;
isBuyer: boolean;
}
export function RatingModal({
isOpen,
onClose,
tradeId,
counterpartyId,
counterpartyWallet,
isBuyer,
}: RatingModalProps) {
const { user } = useAuth();
const [rating, setRating] = useState(0);
const [hoveredRating, setHoveredRating] = useState(0);
const [review, setReview] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async () => {
if (!user || rating === 0) {
toast.error('Please select a rating');
return;
}
setLoading(true);
try {
// Check if already rated
const { data: existingRating } = await supabase
.from('p2p_ratings')
.select('id')
.eq('trade_id', tradeId)
.eq('rater_id', user.id)
.single();
if (existingRating) {
toast.error('You have already rated this trade');
onClose();
return;
}
// Insert rating
const { error: ratingError } = await supabase.from('p2p_ratings').insert({
trade_id: tradeId,
rater_id: user.id,
rated_id: counterpartyId,
rating,
review: review.trim() || null,
});
if (ratingError) throw ratingError;
// Update reputation score
const { data: repData } = await supabase
.from('p2p_reputation')
.select('*')
.eq('user_id', counterpartyId)
.single();
if (repData) {
// Calculate new average rating
const { data: allRatings } = await supabase
.from('p2p_ratings')
.select('rating')
.eq('rated_id', counterpartyId);
const totalRatings = allRatings?.length || 0;
const avgRating = allRatings
? allRatings.reduce((sum, r) => sum + r.rating, 0) / totalRatings
: rating;
// Update reputation
await supabase
.from('p2p_reputation')
.update({
reputation_score: Math.round(avgRating * 20), // Convert 5-star to 100-point scale
})
.eq('user_id', counterpartyId);
}
// Create notification
await supabase.from('p2p_notifications').insert({
user_id: counterpartyId,
type: 'new_rating',
title: 'New Rating Received',
message: `You received a ${rating}-star rating`,
reference_type: 'trade',
reference_id: tradeId,
is_read: false,
});
toast.success('Rating submitted successfully');
onClose();
} catch (error) {
console.error('Submit rating error:', error);
toast.error('Failed to submit rating');
} finally {
setLoading(false);
}
};
const renderStars = () => {
return (
<div className="flex items-center gap-1">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
type="button"
onClick={() => setRating(star)}
onMouseEnter={() => setHoveredRating(star)}
onMouseLeave={() => setHoveredRating(0)}
className="p-1 transition-transform hover:scale-110"
>
<Star
className={`w-8 h-8 transition-colors ${
star <= (hoveredRating || rating)
? 'fill-yellow-400 text-yellow-400'
: 'text-gray-600'
}`}
/>
</button>
))}
</div>
);
};
const getRatingLabel = (r: number): string => {
switch (r) {
case 1: return 'Poor';
case 2: return 'Fair';
case 3: return 'Good';
case 4: return 'Very Good';
case 5: return 'Excellent';
default: return 'Select a rating';
}
};
const quickReviews = [
{ icon: ThumbsUp, text: 'Fast payment', positive: true },
{ icon: ThumbsUp, text: 'Good communication', positive: true },
{ icon: ThumbsUp, text: 'Smooth transaction', positive: true },
{ icon: ThumbsDown, text: 'Slow response', positive: false },
{ icon: ThumbsDown, text: 'Delayed payment', positive: false },
];
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="bg-gray-900 border-gray-800 text-white max-w-md">
<DialogHeader>
<DialogTitle>Rate Your Experience</DialogTitle>
<DialogDescription className="text-gray-400">
How was your trade with {counterpartyWallet.slice(0, 6)}...{counterpartyWallet.slice(-4)}?
</DialogDescription>
</DialogHeader>
<div className="space-y-6 py-4">
{/* Star Rating */}
<div className="flex flex-col items-center gap-2">
{renderStars()}
<p className={`text-sm font-medium ${
rating >= 4 ? 'text-green-400' :
rating >= 3 ? 'text-yellow-400' :
rating >= 1 ? 'text-red-400' : 'text-gray-500'
}`}>
{getRatingLabel(hoveredRating || rating)}
</p>
</div>
{/* Quick Review Buttons */}
<div>
<Label className="text-gray-400 text-sm">Quick feedback (optional)</Label>
<div className="flex flex-wrap gap-2 mt-2">
{quickReviews.map((qr, i) => (
<button
key={i}
type="button"
onClick={() => setReview(prev =>
prev ? `${prev}, ${qr.text}` : qr.text
)}
className={`
flex items-center gap-1 px-3 py-1.5 rounded-full text-sm
border transition-colors
${qr.positive
? 'border-green-500/30 text-green-400 hover:bg-green-500/10'
: 'border-red-500/30 text-red-400 hover:bg-red-500/10'
}
`}
>
<qr.icon className="w-3 h-3" />
{qr.text}
</button>
))}
</div>
</div>
{/* Review Text */}
<div>
<Label htmlFor="review" className="text-gray-400 text-sm">
Additional comments (optional)
</Label>
<Textarea
id="review"
value={review}
onChange={(e) => setReview(e.target.value)}
placeholder="Share your experience..."
className="mt-2 bg-gray-800 border-gray-700 text-white placeholder:text-gray-500 resize-none"
rows={3}
maxLength={500}
/>
<p className="text-xs text-gray-500 text-right mt-1">
{review.length}/500
</p>
</div>
{/* Role Badge */}
<div className="flex items-center justify-center">
<span className={`
px-3 py-1 rounded-full text-xs
${isBuyer
? 'bg-green-500/20 text-green-400'
: 'bg-blue-500/20 text-blue-400'
}
`}>
Rating as {isBuyer ? 'Buyer' : 'Seller'}
</span>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={onClose}
disabled={loading}
className="border-gray-700"
>
Skip
</Button>
<Button
onClick={handleSubmit}
disabled={rating === 0 || loading}
className="bg-green-600 hover:bg-green-700"
>
{loading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Submitting...
</>
) : (
'Submit Rating'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+415
View File
@@ -0,0 +1,415 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
Send,
Image as ImageIcon,
Loader2,
AlertCircle,
CheckCheck,
Clock,
Bot,
} from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';
import { supabase } from '@/lib/supabase';
interface Message {
id: string;
trade_id: string;
sender_id: string;
message: string;
message_type: 'text' | 'image' | 'system';
attachment_url?: string;
is_read: boolean;
created_at: string;
}
interface TradeChatProps {
tradeId: string;
counterpartyId: string;
counterpartyWallet: string;
isTradeActive: boolean;
}
export function TradeChat({
tradeId,
counterpartyId,
counterpartyWallet,
isTradeActive,
}: TradeChatProps) {
const { user } = useAuth();
const [messages, setMessages] = useState<Message[]>([]);
const [newMessage, setNewMessage] = useState('');
const [loading, setLoading] = useState(true);
const [sending, setSending] = useState(false);
const [uploading, setUploading] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// Scroll to bottom
const scrollToBottom = useCallback(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, []);
// Fetch messages
const fetchMessages = useCallback(async () => {
try {
const { data, error } = await supabase
.from('p2p_messages')
.select('*')
.eq('trade_id', tradeId)
.order('created_at', { ascending: true });
if (error) throw error;
setMessages(data || []);
// Mark messages as read
if (user && data && data.length > 0) {
const unreadIds = data
.filter(m => m.sender_id !== user.id && !m.is_read)
.map(m => m.id);
if (unreadIds.length > 0) {
await supabase
.from('p2p_messages')
.update({ is_read: true })
.in('id', unreadIds);
}
}
} catch (error) {
console.error('Fetch messages error:', error);
} finally {
setLoading(false);
}
}, [tradeId, user]);
// Initial fetch
useEffect(() => {
fetchMessages();
}, [fetchMessages]);
// Real-time subscription
useEffect(() => {
const channel = supabase
.channel(`chat-${tradeId}`)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'p2p_messages',
filter: `trade_id=eq.${tradeId}`,
},
(payload) => {
const newMsg = payload.new as Message;
setMessages(prev => {
// Avoid duplicates
if (prev.some(m => m.id === newMsg.id)) return prev;
return [...prev, newMsg];
});
// Mark as read if from counterparty
if (user && newMsg.sender_id !== user.id) {
supabase
.from('p2p_messages')
.update({ is_read: true })
.eq('id', newMsg.id);
}
}
)
.subscribe();
return () => {
supabase.removeChannel(channel);
};
}, [tradeId, user]);
// Scroll to bottom on new messages
useEffect(() => {
scrollToBottom();
}, [messages, scrollToBottom]);
// Send message
const handleSendMessage = async () => {
if (!newMessage.trim() || !user || sending) return;
const messageText = newMessage.trim();
setNewMessage('');
setSending(true);
try {
const { error } = await supabase.from('p2p_messages').insert({
trade_id: tradeId,
sender_id: user.id,
message: messageText,
message_type: 'text',
is_read: false,
});
if (error) throw error;
// Create notification for counterparty
await supabase.from('p2p_notifications').insert({
user_id: counterpartyId,
type: 'new_message',
title: 'New Message',
message: messageText.slice(0, 100),
reference_type: 'trade',
reference_id: tradeId,
is_read: false,
});
} catch (error) {
console.error('Send message error:', error);
toast.error('Failed to send message');
setNewMessage(messageText); // Restore message
} finally {
setSending(false);
}
};
// Handle Enter key
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
};
// Upload image
const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file || !user) return;
// Validate file
if (!file.type.startsWith('image/')) {
toast.error('Please select an image file');
return;
}
if (file.size > 5 * 1024 * 1024) {
toast.error('Image must be less than 5MB');
return;
}
setUploading(true);
try {
// Upload to Supabase Storage
const fileName = `${tradeId}/${Date.now()}-${file.name}`;
const { data: uploadData, error: uploadError } = await supabase.storage
.from('p2p-chat-images')
.upload(fileName, file);
if (uploadError) throw uploadError;
// Get public URL
const { data: urlData } = supabase.storage
.from('p2p-chat-images')
.getPublicUrl(uploadData.path);
// Insert message with image
const { error: msgError } = await supabase.from('p2p_messages').insert({
trade_id: tradeId,
sender_id: user.id,
message: 'Sent an image',
message_type: 'image',
attachment_url: urlData.publicUrl,
is_read: false,
});
if (msgError) throw msgError;
// Create notification
await supabase.from('p2p_notifications').insert({
user_id: counterpartyId,
type: 'new_message',
title: 'New Image',
message: 'Sent an image',
reference_type: 'trade',
reference_id: tradeId,
is_read: false,
});
toast.success('Image sent');
} catch (error) {
console.error('Upload image error:', error);
toast.error('Failed to upload image');
} finally {
setUploading(false);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
};
// Format timestamp
const formatTime = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};
// Render message
const renderMessage = (message: Message) => {
const isOwn = message.sender_id === user?.id;
const isSystem = message.message_type === 'system';
if (isSystem) {
return (
<div key={message.id} className="flex justify-center my-2">
<div className="flex items-center gap-2 px-3 py-1 bg-gray-800 rounded-full text-xs text-gray-400">
<Bot className="w-3 h-3" />
{message.message}
</div>
</div>
);
}
return (
<div
key={message.id}
className={`flex ${isOwn ? 'justify-end' : 'justify-start'} mb-3`}
>
<div className={`flex items-end gap-2 max-w-[75%] ${isOwn ? 'flex-row-reverse' : ''}`}>
{!isOwn && (
<Avatar className="h-6 w-6">
<AvatarFallback className="bg-gray-700 text-xs">
{counterpartyWallet.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
)}
<div>
<div
className={`
px-3 py-2 rounded-2xl
${isOwn
? 'bg-green-600 text-white rounded-br-sm'
: 'bg-gray-700 text-white rounded-bl-sm'
}
`}
>
{message.message_type === 'image' && message.attachment_url ? (
<a
href={message.attachment_url}
target="_blank"
rel="noopener noreferrer"
>
<img
src={message.attachment_url}
alt="Shared image"
className="max-w-[200px] max-h-[200px] rounded-lg"
/>
</a>
) : (
<p className="text-sm whitespace-pre-wrap break-words">{message.message}</p>
)}
</div>
<div className={`flex items-center gap-1 mt-1 ${isOwn ? 'justify-end' : ''}`}>
<span className="text-xs text-gray-500">{formatTime(message.created_at)}</span>
{isOwn && (
message.is_read ? (
<CheckCheck className="w-3 h-3 text-blue-400" />
) : (
<Clock className="w-3 h-3 text-gray-500" />
)
)}
</div>
</div>
</div>
</div>
);
};
return (
<Card className="bg-gray-900 border-gray-800 h-[400px] flex flex-col">
<CardHeader className="py-3 px-4 border-b border-gray-800">
<CardTitle className="text-white text-base flex items-center gap-2">
<span>Chat</span>
{messages.filter(m => m.sender_id !== user?.id && !m.is_read).length > 0 && (
<span className="px-1.5 py-0.5 text-xs bg-green-500 text-white rounded-full">
{messages.filter(m => m.sender_id !== user?.id && !m.is_read).length}
</span>
)}
</CardTitle>
</CardHeader>
<CardContent className="flex-1 flex flex-col p-0 overflow-hidden">
{/* Messages */}
<ScrollArea className="flex-1 p-4" ref={scrollRef}>
{loading ? (
<div className="flex items-center justify-center h-full">
<Loader2 className="w-6 h-6 animate-spin text-gray-500" />
</div>
) : messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-gray-500">
<AlertCircle className="w-8 h-8 mb-2" />
<p className="text-sm">No messages yet</p>
<p className="text-xs">Start the conversation</p>
</div>
) : (
messages.map(renderMessage)
)}
</ScrollArea>
{/* Input */}
{isTradeActive ? (
<div className="p-3 border-t border-gray-800">
<div className="flex items-center gap-2">
<input
type="file"
accept="image/*"
ref={fileInputRef}
onChange={handleImageUpload}
className="hidden"
/>
<Button
variant="ghost"
size="sm"
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="text-gray-400 hover:text-white"
>
{uploading ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<ImageIcon className="w-5 h-5" />
)}
</Button>
<Input
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="Type a message..."
disabled={sending}
className="flex-1 bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
/>
<Button
size="sm"
onClick={handleSendMessage}
disabled={!newMessage.trim() || sending}
className="bg-green-600 hover:bg-green-700"
>
{sending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Send className="w-4 h-4" />
)}
</Button>
</div>
</div>
) : (
<div className="p-3 border-t border-gray-800 text-center">
<p className="text-sm text-gray-500">
Chat is disabled for completed/cancelled trades
</p>
</div>
)}
</CardContent>
</Card>
);
}
+204
View File
@@ -0,0 +1,204 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, AlertTriangle, Clock } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { usePezkuwi } from '@/contexts/PezkuwiContext';
import { toast } from 'sonner';
import { acceptFiatOffer, type P2PFiatOffer } from '@shared/lib/p2p-fiat';
interface TradeModalProps {
offer: P2PFiatOffer;
onClose: () => void;
}
export function TradeModal({ offer, onClose }: TradeModalProps) {
const navigate = useNavigate();
const { user } = useAuth();
const { api, selectedAccount } = usePezkuwi();
const [amount, setAmount] = useState('');
const [loading, setLoading] = useState(false);
const cryptoAmount = parseFloat(amount) || 0;
const fiatAmount = cryptoAmount * offer.price_per_unit;
const isValidAmount = cryptoAmount > 0 && cryptoAmount <= offer.remaining_amount;
// Check min/max order amounts
const meetsMinOrder = !offer.min_order_amount || cryptoAmount >= offer.min_order_amount;
const meetsMaxOrder = !offer.max_order_amount || cryptoAmount <= offer.max_order_amount;
const handleInitiateTrade = async () => {
if (!api || !selectedAccount || !user) {
toast.error('Please connect your wallet and log in');
return;
}
// Prevent self-trading
if (offer.seller_id === user.id) {
toast.error('You cannot trade with your own offer');
return;
}
if (!isValidAmount) {
toast.error('Invalid amount');
return;
}
if (!meetsMinOrder) {
toast.error(`Minimum order: ${offer.min_order_amount} ${offer.token}`);
return;
}
if (!meetsMaxOrder) {
toast.error(`Maximum order: ${offer.max_order_amount} ${offer.token}`);
return;
}
setLoading(true);
try {
const tradeId = await acceptFiatOffer({
api,
account: selectedAccount,
offerId: offer.id,
amount: cryptoAmount
});
toast.success('Trade initiated! Proceed to payment.');
onClose();
// Navigate to trade page
navigate(`/p2p/trade/${tradeId}`);
} catch (error) {
if (import.meta.env.DEV) console.error('Accept offer error:', error);
// Error toast already shown in acceptFiatOffer
} finally {
setLoading(false);
}
};
return (
<Dialog open={true} onOpenChange={onClose}>
<DialogContent className="bg-gray-900 border-gray-800 text-white max-w-md">
<DialogHeader>
<DialogTitle>Buy {offer.token}</DialogTitle>
<DialogDescription className="text-gray-400">
Trading with {offer.seller_wallet.slice(0, 6)}...{offer.seller_wallet.slice(-4)}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{/* Price Info */}
<div className="p-4 bg-gray-800 rounded-lg">
<div className="flex justify-between items-center mb-2">
<span className="text-gray-400">Price</span>
<span className="text-xl font-bold text-green-400">
{offer.price_per_unit.toFixed(2)} {offer.fiat_currency}
</span>
</div>
<div className="flex justify-between items-center text-sm">
<span className="text-gray-400">Available</span>
<span className="text-white">{offer.remaining_amount} {offer.token}</span>
</div>
</div>
{/* Amount Input */}
<div>
<Label htmlFor="buyAmount">Amount to Buy ({offer.token})</Label>
<Input
id="buyAmount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Amount"
className="bg-gray-800 border-gray-700 text-white placeholder:text-gray-500 placeholder:opacity-50"
/>
{offer.min_order_amount && (
<p className="text-xs text-gray-500 mt-1">
Min: {offer.min_order_amount} {offer.token}
</p>
)}
{offer.max_order_amount && (
<p className="text-xs text-gray-500 mt-1">
Max: {offer.max_order_amount} {offer.token}
</p>
)}
</div>
{/* Calculation */}
{cryptoAmount > 0 && (
<div className="p-4 bg-green-500/10 border border-green-500/30 rounded-lg">
<p className="text-sm text-gray-400 mb-1">You will pay</p>
<p className="text-2xl font-bold text-green-400">
{fiatAmount.toFixed(2)} {offer.fiat_currency}
</p>
</div>
)}
{/* Warnings */}
{!meetsMinOrder && cryptoAmount > 0 && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Minimum order: {offer.min_order_amount} {offer.token}
</AlertDescription>
</Alert>
)}
{!meetsMaxOrder && cryptoAmount > 0 && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Maximum order: {offer.max_order_amount} {offer.token}
</AlertDescription>
</Alert>
)}
{/* Payment Time Limit */}
<Alert>
<Clock className="h-4 w-4" />
<AlertDescription>
Payment deadline: {offer.time_limit_minutes} minutes after accepting
</AlertDescription>
</Alert>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={onClose}
disabled={loading}
className="bg-gray-800 border-gray-700 hover:bg-gray-700"
>
Cancel
</Button>
<Button
onClick={handleInitiateTrade}
disabled={!isValidAmount || !meetsMinOrder || !meetsMaxOrder || loading}
>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Initiating...
</>
) : (
'Accept & Continue'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+458
View File
@@ -0,0 +1,458 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import {
Loader2,
CheckCircle2,
AlertTriangle,
ArrowUpFromLine,
Clock,
Info
} from 'lucide-react';
import { usePezkuwi } from '@/contexts/PezkuwiContext';
import { toast } from 'sonner';
import {
getInternalBalances,
requestWithdraw,
getDepositWithdrawHistory,
type CryptoToken,
type InternalBalance,
type DepositWithdrawRequest
} from '@shared/lib/p2p-fiat';
interface WithdrawModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess?: () => void;
}
type WithdrawStep = 'form' | 'confirm' | 'success';
export function WithdrawModal({ isOpen, onClose, onSuccess }: WithdrawModalProps) {
const { selectedAccount } = usePezkuwi();
const [step, setStep] = useState<WithdrawStep>('form');
const [token, setToken] = useState<CryptoToken>('HEZ');
const [amount, setAmount] = useState('');
const [walletAddress, setWalletAddress] = useState('');
const [balances, setBalances] = useState<InternalBalance[]>([]);
const [pendingRequests, setPendingRequests] = useState<DepositWithdrawRequest[]>([]);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [requestId, setRequestId] = useState<string>('');
// Network fee estimate (in HEZ)
const NETWORK_FEE = 0.01;
const MIN_WITHDRAWAL = 0.1;
// Fetch balances and pending requests on mount
useEffect(() => {
if (isOpen) {
fetchData();
// Pre-fill wallet address from connected account
if (selectedAccount?.address) {
setWalletAddress(selectedAccount.address);
}
}
}, [isOpen, selectedAccount]);
const fetchData = async () => {
setLoading(true);
try {
const [balanceData, historyData] = await Promise.all([
getInternalBalances(),
getDepositWithdrawHistory()
]);
setBalances(balanceData);
// Filter for pending withdrawal requests
setPendingRequests(
historyData.filter(r => r.request_type === 'withdraw' && r.status === 'pending')
);
} catch (error) {
console.error('Fetch data error:', error);
} finally {
setLoading(false);
}
};
const resetModal = () => {
setStep('form');
setAmount('');
setSubmitting(false);
setRequestId('');
};
const handleClose = () => {
resetModal();
onClose();
};
const getAvailableBalance = (): number => {
const balance = balances.find(b => b.token === token);
return balance?.available_balance || 0;
};
const getLockedBalance = (): number => {
const balance = balances.find(b => b.token === token);
return balance?.locked_balance || 0;
};
const getMaxWithdrawable = (): number => {
const available = getAvailableBalance();
// Subtract network fee for HEZ
if (token === 'HEZ') {
return Math.max(0, available - NETWORK_FEE);
}
return available;
};
const handleSetMax = () => {
const max = getMaxWithdrawable();
setAmount(max.toFixed(4));
};
const validateWithdrawal = (): string | null => {
const withdrawAmount = parseFloat(amount);
if (isNaN(withdrawAmount) || withdrawAmount <= 0) {
return 'Please enter a valid amount';
}
if (withdrawAmount < MIN_WITHDRAWAL) {
return `Minimum withdrawal is ${MIN_WITHDRAWAL} ${token}`;
}
if (withdrawAmount > getMaxWithdrawable()) {
return 'Insufficient available balance';
}
if (!walletAddress || walletAddress.length < 40) {
return 'Please enter a valid wallet address';
}
// Check for pending requests
const hasPendingForToken = pendingRequests.some(r => r.token === token);
if (hasPendingForToken) {
return `You already have a pending ${token} withdrawal request`;
}
return null;
};
const handleContinue = () => {
const error = validateWithdrawal();
if (error) {
toast.error(error);
return;
}
setStep('confirm');
};
const handleSubmitWithdrawal = async () => {
const error = validateWithdrawal();
if (error) {
toast.error(error);
return;
}
setSubmitting(true);
try {
const withdrawAmount = parseFloat(amount);
const id = await requestWithdraw(token, withdrawAmount, walletAddress);
setRequestId(id);
setStep('success');
onSuccess?.();
} catch (error) {
console.error('Submit withdrawal error:', error);
} finally {
setSubmitting(false);
}
};
const renderFormStep = () => (
<div className="space-y-6">
{loading ? (
<div className="space-y-4">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</div>
) : (
<>
{/* Token Selection */}
<div className="space-y-2">
<Label>Select Token</Label>
<Select value={token} onValueChange={(v) => setToken(v as CryptoToken)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="HEZ">HEZ (Native)</SelectItem>
<SelectItem value="PEZ">PEZ</SelectItem>
</SelectContent>
</Select>
</div>
{/* Balance Display */}
<div className="p-4 rounded-lg bg-muted/50 border">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<p className="text-muted-foreground">Available</p>
<p className="font-semibold text-green-500">
{getAvailableBalance().toFixed(4)} {token}
</p>
</div>
<div>
<p className="text-muted-foreground">Locked (Escrow)</p>
<p className="font-semibold text-yellow-500">
{getLockedBalance().toFixed(4)} {token}
</p>
</div>
</div>
</div>
{/* Amount Input */}
<div className="space-y-2">
<Label>Withdrawal Amount</Label>
<div className="relative">
<Input
type="number"
placeholder="0.00"
value={amount}
onChange={(e) => setAmount(e.target.value)}
min="0"
step="0.0001"
/>
<div className="absolute right-14 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
{token}
</div>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-2 top-1/2 -translate-y-1/2 h-7 text-xs"
onClick={handleSetMax}
>
MAX
</Button>
</div>
<p className="text-xs text-muted-foreground">
Min: {MIN_WITHDRAWAL} {token} | Max: {getMaxWithdrawable().toFixed(4)} {token}
</p>
</div>
{/* Wallet Address */}
<div className="space-y-2">
<Label>Destination Wallet Address</Label>
<Input
value={walletAddress}
onChange={(e) => setWalletAddress(e.target.value)}
placeholder="5..."
className="font-mono text-xs"
/>
<p className="text-xs text-muted-foreground">
Only PezkuwiChain addresses are supported
</p>
</div>
{/* Network Fee Info */}
{token === 'HEZ' && (
<Alert>
<Info className="h-4 w-4" />
<AlertDescription>
Network fee: ~{NETWORK_FEE} HEZ (deducted from withdrawal amount)
</AlertDescription>
</Alert>
)}
{/* Pending Requests Warning */}
{pendingRequests.length > 0 && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
You have {pendingRequests.length} pending withdrawal request(s).
Please wait for them to complete.
</AlertDescription>
</Alert>
)}
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={handleContinue}
disabled={!amount || parseFloat(amount) <= 0}
>
Continue
</Button>
</DialogFooter>
</>
)}
</div>
);
const renderConfirmStep = () => {
const withdrawAmount = parseFloat(amount);
const receiveAmount = token === 'HEZ' ? withdrawAmount - NETWORK_FEE : withdrawAmount;
return (
<div className="space-y-6">
<Alert>
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Please review your withdrawal details carefully.
This action cannot be undone.
</AlertDescription>
</Alert>
<div className="p-4 rounded-lg bg-muted/50 border space-y-4">
<div className="flex justify-between items-center">
<span className="text-muted-foreground">Token</span>
<span className="font-semibold">{token}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-muted-foreground">Withdrawal Amount</span>
<span className="font-semibold">{withdrawAmount.toFixed(4)} {token}</span>
</div>
{token === 'HEZ' && (
<div className="flex justify-between items-center">
<span className="text-muted-foreground">Network Fee</span>
<span className="text-yellow-500">-{NETWORK_FEE} HEZ</span>
</div>
)}
<div className="border-t pt-4 flex justify-between items-center">
<span className="text-muted-foreground">You Will Receive</span>
<span className="font-bold text-lg text-green-500">
{receiveAmount.toFixed(4)} {token}
</span>
</div>
</div>
<div className="p-4 rounded-lg bg-muted/30 border">
<p className="text-xs text-muted-foreground mb-1">Destination Address</p>
<p className="font-mono text-xs break-all">{walletAddress}</p>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="h-4 w-4" />
<span>Processing time: Usually within 5-30 minutes</span>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setStep('form')}>
Back
</Button>
<Button
onClick={handleSubmitWithdrawal}
disabled={submitting}
>
{submitting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Processing...
</>
) : (
<>
<ArrowUpFromLine className="h-4 w-4 mr-2" />
Confirm Withdrawal
</>
)}
</Button>
</DialogFooter>
</div>
);
};
const renderSuccessStep = () => (
<div className="space-y-6 text-center">
<div className="w-20 h-20 mx-auto rounded-full bg-green-500/10 flex items-center justify-center">
<CheckCircle2 className="h-10 w-10 text-green-500" />
</div>
<div>
<h3 className="text-xl font-semibold text-green-500">
Withdrawal Request Submitted!
</h3>
<p className="text-muted-foreground mt-2">
Your withdrawal request has been submitted for processing.
</p>
</div>
<div className="p-4 rounded-lg bg-muted/50 border space-y-3">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Request ID</span>
<Badge variant="outline" className="font-mono text-xs">
{requestId.slice(0, 8)}...
</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Status</span>
<Badge className="bg-yellow-500/20 text-yellow-500 border-yellow-500/30">
<Clock className="h-3 w-3 mr-1" />
Processing
</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Amount</span>
<span className="font-semibold">{amount} {token}</span>
</div>
</div>
<Alert>
<Info className="h-4 w-4" />
<AlertDescription>
You can track your withdrawal status in the transaction history.
Funds will arrive in your wallet within 5-30 minutes.
</AlertDescription>
</Alert>
<Button onClick={handleClose} className="w-full">
Done
</Button>
</div>
);
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<ArrowUpFromLine className="h-5 w-5" />
Withdraw from P2P Balance
</DialogTitle>
{step !== 'success' && (
<DialogDescription>
{step === 'form' && 'Withdraw crypto from your P2P balance to external wallet'}
{step === 'confirm' && 'Review and confirm your withdrawal'}
</DialogDescription>
)}
</DialogHeader>
{step === 'form' && renderFormStep()}
{step === 'confirm' && renderConfirmStep()}
{step === 'success' && renderSuccessStep()}
</DialogContent>
</Dialog>
);
}
+46
View File
@@ -0,0 +1,46 @@
// P2P Filter types and defaults - separate file to avoid react-refresh warning
export interface P2PFilters {
// Token
token: 'HEZ' | 'PEZ' | 'all';
// Fiat currency
fiatCurrency: string | 'all';
// Payment methods
paymentMethods: string[];
// Amount range
minAmount: number | null;
maxAmount: number | null;
// Merchant tier
merchantTiers: ('lite' | 'super' | 'diamond')[];
// Completion rate
minCompletionRate: number;
// Online status
onlineOnly: boolean;
// Verified only
verifiedOnly: boolean;
// Sort
sortBy: 'price' | 'completion_rate' | 'trades' | 'newest';
sortOrder: 'asc' | 'desc';
}
export const DEFAULT_FILTERS: P2PFilters = {
token: 'all',
fiatCurrency: 'all',
paymentMethods: [],
minAmount: null,
maxAmount: null,
merchantTiers: [],
minCompletionRate: 0,
onlineOnly: false,
verifiedOnly: false,
sortBy: 'price',
sortOrder: 'asc'
};
+56
View File
@@ -0,0 +1,56 @@
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 border-border/50", 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:text-primary [&[data-state=open]>svg]:rotate-180 [&[data-state=open]]:text-primary",
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-300 ease-in-out text-muted-foreground" />
</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 text-muted-foreground 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 }
+139
View File
@@ -0,0 +1,139 @@
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-background/80 backdrop-blur-sm 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-card 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 mt-4",
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 text-primary/90", 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 mt-2", 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,
}
+65
View File
@@ -0,0 +1,65 @@
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 shadow-sm",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
success:
"border-green-500/50 text-green-600 dark:text-green-400 [&>svg]:text-green-600 dark:[&>svg]:text-green-400 bg-green-50 dark:bg-green-950/20",
warning:
"border-yellow-500/50 text-yellow-600 dark:text-yellow-400 [&>svg]:text-yellow-600 dark:[&>svg]:text-yellow-400 bg-yellow-50 dark:bg-yellow-950/20",
info:
"border-primary/50 text-primary dark:text-primary-foreground [&>svg]:text-primary bg-primary/10 dark:bg-primary/20",
},
},
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 opacity-90", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }
+5
View File
@@ -0,0 +1,5 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
const AspectRatio = AspectRatioPrimitive.Root
export { AspectRatio }
+54
View File
@@ -0,0 +1,54 @@
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> & {
size?: "sm" | "md" | "lg" | "xl"
}
>(({ className, size = "md", ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex shrink-0 overflow-hidden rounded-full border border-border/30 ring-offset-background",
size === "sm" && "h-8 w-8",
size === "md" && "h-10 w-10",
size === "lg" && "h-12 w-12",
size === "xl" && "h-16 w-16",
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 object-cover", 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 text-muted-foreground",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }
+13
View File
@@ -0,0 +1,13 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import { Badge } from './badge';
describe('Badge Component', () => {
it('should render the badge with the correct text', () => {
const testMessage = 'Hello, World!';
render(<Badge>{testMessage}</Badge>);
const badgeElement = screen.getByText(testMessage);
expect(badgeElement).toBeInTheDocument();
});
});
+48
View File
@@ -0,0 +1,48 @@
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-all focus:outline-none focus:ring-2 focus:ring-primary 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 border-border",
success:
"border-transparent bg-green-500/20 text-green-700 dark:text-green-300 border-green-500/30",
warning:
"border-transparent bg-yellow-500/20 text-yellow-700 dark:text-yellow-300 border-yellow-500/30",
info:
"border-transparent bg-primary/10 text-primary border-primary/30",
},
size: {
default: "px-2.5 py-0.5 text-xs",
sm: "px-2 py-0.5 text-[10px]",
lg: "px-3 py-0.5 text-sm",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, size, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant, size }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+115
View File
@@ -0,0 +1,115 @@
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-primary focus-visible:text-primary", 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-medium 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 text-muted-foreground/50", className)}
{...props}
>
{children ?? <ChevronRight className="h-3.5 w-3.5" />}
</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 text-muted-foreground", 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,
}
+56
View File
@@ -0,0 +1,56 @@
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 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",
{
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 }
+64
View File
@@ -0,0 +1,64 @@
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 text-foreground",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline", size: "sm" }),
"h-7 w-7 bg-transparent p-0 opacity-70 hover:opacity-100 transition-opacity"
),
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", size: "sm" }),
"h-9 w-9 p-0 font-normal aria-selected:opacity-100 hover:text-accent-foreground"
),
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 rounded-md transition-colors",
day_today: "bg-accent/50 text-accent-foreground rounded-md",
day_outside:
"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/30 aria-selected:text-muted-foreground aria-selected:opacity-40",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent/60 aria-selected:text-accent-foreground rounded-none",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: () => <ChevronLeft className="h-4 w-4" />,
IconRight: () => <ChevronRight className="h-4 w-4" />,
}}
{...props}
/>
);
}
Calendar.displayName = "Calendar";
export { Calendar };
+79
View File
@@ -0,0 +1,79 @@
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 border-border/40 bg-background 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 text-foreground",
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 }
+260
View File
@@ -0,0 +1,260 @@
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 border border-border/40 opacity-80 hover:opacity-100 transition-opacity",
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 border border-border/40 opacity-80 hover:opacity-100 transition-opacity",
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,
}
+363
View File
@@ -0,0 +1,363 @@
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "@/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
}
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
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/40 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border/60 [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border/40 [&_.recharts-radial-bar-background-sector]:fill-muted/50 [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted/80 [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border/40 [&_.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/95 backdrop-blur-sm 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 && (
<span className="font-mono font-medium tabular-nums text-foreground">
{item.value.toLocaleString()}
</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,
}
+28
View File
@@ -0,0 +1,28 @@
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/60 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground transition-colors duration-200",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-3.5 w-3.5 transition-transform duration-200" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }
+9
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 }
+151
View File
@@ -0,0 +1,151 @@
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
const CommandDialog = ({ children, ...props }: DialogProps) => {
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 [&_[data-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 border-border/40 px-3" data-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/60 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 text-muted-foreground"
{...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/60", 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/60 data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 transition-colors",
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/70",
className
)}
{...props}
/>
)
}
CommandShortcut.displayName = "CommandShortcut"
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}
+198
View File
@@ -0,0 +1,198 @@
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 focus:bg-accent/60 focus:text-accent-foreground data-[state=open]:bg-accent/60 data-[state=open]:text-accent-foreground transition-colors",
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 border-border/40 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 duration-200",
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 border-border/40 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 duration-200",
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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 transition-colors",
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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 transition-colors",
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 text-primary" />
</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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 transition-colors",
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 text-primary" />
</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-medium 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/60", 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/70",
className
)}
{...props}
/>
)
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}
+120
View File
@@ -0,0 +1,120 @@
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-background/80 backdrop-blur-sm 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 border-border/40 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 hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<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 text-foreground",
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,
}
+116
View File
@@ -0,0 +1,116 @@
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-background/80 backdrop-blur-sm", 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 border-border bg-card shadow-lg",
className
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted/50" />
{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 text-primary/90",
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 mt-2", className)}
{...props}
/>
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}
+198
View File
@@ -0,0 +1,198 @@
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 focus:bg-accent/60 focus:text-accent-foreground data-[state=open]:bg-accent/60 data-[state=open]:text-accent-foreground transition-colors",
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 border-border/40 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 duration-200",
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 border-border/40 bg-popover/95 backdrop-blur-sm 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 duration-200",
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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
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 text-primary" />
</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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
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 text-primary" />
</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-medium text-foreground/80",
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-border/60", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest text-muted-foreground/70", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}
+176
View File
@@ -0,0 +1,176 @@
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 mb-4", 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", "text-sm font-medium mb-1", 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/80 mt-1", 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 mt-1", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}
+27
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 border-border/40 bg-popover/95 backdrop-blur-sm 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 duration-200",
className
)}
{...props}
/>
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName
export { HoverCard, HoverCardTrigger, HoverCardContent }
+69
View File
@@ -0,0 +1,69 @@
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 bg-background/50 text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-1 ring-primary ring-offset-background border-primary/50",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-primary duration-700" />
</div>
)}
</div>
)
})
InputOTPSlot.displayName = "InputOTPSlot"
const InputOTPSeparator = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ ...props }, ref) => (
<div ref={ref} role="separator" {...props} className="text-muted-foreground">
<Dot className="h-4 w-4" />
</div>
))
InputOTPSeparator.displayName = "InputOTPSeparator"
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react"
import { cn } from "@/lib/utils"
type InputProps = React.InputHTMLAttributes<HTMLInputElement>
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-border/60 bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium 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}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+43
View File
@@ -0,0 +1,43 @@
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",
{
variants: {
variant: {
default: "text-foreground",
muted: "text-muted-foreground",
accent: "text-primary",
},
size: {
default: "text-sm",
xs: "text-xs",
sm: "text-sm",
lg: "text-base",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, variant, size, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants({ variant, size }), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+234
View File
@@ -0,0 +1,234 @@
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 border-border/50 bg-background/50 p-1 shadow-sm",
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 focus:bg-accent/60 focus:text-accent-foreground data-[state=open]:bg-accent/60 data-[state=open]:text-accent-foreground transition-colors",
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 focus:bg-accent/60 focus:text-accent-foreground data-[state=open]:bg-accent/60 data-[state=open]:text-accent-foreground transition-colors",
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 border-border/40 bg-popover/95 backdrop-blur-sm 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 duration-200",
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 border-border/40 bg-popover/95 backdrop-blur-sm 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 duration-200",
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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 transition-colors",
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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 transition-colors",
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 text-primary" />
</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 focus:bg-accent/60 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 transition-colors",
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 text-primary" />
</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-medium text-foreground/80",
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-border/60", 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/70",
className
)}
{...props}
/>
)
}
MenubarShortcut.displayname = "MenubarShortcut"
export {
Menubar,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarItem,
MenubarSeparator,
MenubarLabel,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarPortal,
MenubarSubContent,
MenubarSubTrigger,
MenubarGroup,
MenubarSub,
MenubarShortcut,
}
+128
View File
@@ -0,0 +1,128 @@
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/50 px-4 py-2 text-sm font-medium transition-all hover:bg-accent/50 hover:text-accent-foreground focus:bg-accent/50 focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/60 data-[state=open]:bg-accent/60"
)
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-300 ease-in-out 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 duration-200 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 border-border/40 bg-popover/95 backdrop-blur-sm 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-primary/20 shadow-md" />
</NavigationMenuPrimitive.Indicator>
))
NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
}
+119
View File
@@ -0,0 +1,119 @@
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,
}),
isActive && "border-primary/50 bg-primary/5 text-primary hover:bg-primary/10",
"transition-colors",
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 hover:text-primary", 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 hover:text-primary", 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 text-muted-foreground", 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,
}
+29
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 border-border/40 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 duration-200",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent }
+37
View File
@@ -0,0 +1,37 @@
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
interface ProgressProps extends
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> {
variant?: "default" | "success" | "warning" | "error"
}
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
ProgressProps
>(({ className, value, variant = "default", ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-2 w-full overflow-hidden rounded-full bg-secondary/40",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className={cn(
"h-full w-full flex-1 transition-all duration-300 ease-in-out",
variant === "default" && "bg-primary",
variant === "success" && "bg-green-500",
variant === "warning" && "bg-yellow-500",
variant === "error" && "bg-destructive",
)}
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName
export { Progress }
+42
View File
@@ -0,0 +1,42 @@
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/60 text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current animate-in scale-in-0 duration-200" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
})
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
export { RadioGroup, RadioGroupItem }
+43
View File
@@ -0,0 +1,43 @@
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/50 after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary focus-visible:ring-offset-1 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 [&[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 border-border/50 bg-border/30 hover:bg-border/50 transition-colors">
<GripVertical className="h-2.5 w-2.5 text-primary/40" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
)
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
+48
View File
@@ -0,0 +1,48 @@
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> & {
hideScrollbar?: boolean
}
>(({ className, children, hideScrollbar = false, ...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>
{!hideScrollbar && <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 duration-300",
orientation === "vertical" &&
"h-full w-2 border-l border-l-transparent p-[1px] hover:w-2.5",
orientation === "horizontal" &&
"h-2 flex-col border-t border-t-transparent p-[1px] hover:h-2.5",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border/50 hover:bg-border/80 transition-colors" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }
+158
View File
@@ -0,0 +1,158 @@
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/60 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary focus-visible:border-primary/50 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 transition-colors",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50 transition-transform duration-200 ease-in-out group-data-[state=open]:rotate-180" />
</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 text-muted-foreground",
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 text-muted-foreground",
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 border-border/40 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 duration-200",
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-medium text-muted-foreground", 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 focus:bg-accent/50 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 transition-colors",
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 text-primary" />
</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,
}
+37
View File
@@ -0,0 +1,37 @@
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
interface SeparatorProps extends
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root> {
variant?: "default" | "muted" | "accent"
}
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
SeparatorProps
>(
(
{ className, orientation = "horizontal", decorative = true, variant = "default", ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0",
variant === "default" && "bg-border",
variant === "muted" && "bg-muted",
variant === "accent" && "bg-primary/30",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }
+131
View File
@@ -0,0 +1,131 @@
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-background/80 backdrop-blur-sm 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-card border 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 rounded-b-xl data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t rounded-t-xl 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 hover:opacity-100 hover:text-primary focus:outline-none focus:ring-2 focus:ring-primary 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 mt-4",
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-primary/90", 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 mt-2", className)}
{...props}
/>
))
SheetDescription.displayName = SheetPrimitive.Description.displayName
export {
Sheet, SheetClose,
SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger
}
+738
View File
@@ -0,0 +1,738 @@
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 sidebarVariants = cva(
"h-full bg-background/80 backdrop-blur-sm border-r border-border/40 shadow-sm",
{
variants: {
size: {
sm: "w-16",
md: "w-64",
lg: "w-80",
},
collapsible: {
true: "transition-all duration-300 ease-in-out",
},
},
defaultVariants: {
size: "md",
},
}
)
interface SidebarProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof sidebarVariants> {
collapsed?: boolean
}
const Sidebar = React.forwardRef<HTMLDivElement, SidebarProps>(
(
{ className, size, collapsible, collapsed = false, children, ...props },
ref
) => {
const actualSize = collapsed ? "sm" : size
return (
<div
ref={ref}
className={cn(sidebarVariants({ size: actualSize, collapsible }), className)}
{...props}
>
{children}
</div>
)
}
)
Sidebar.displayName = "Sidebar"
const SidebarHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("p-4 border-b border-border/40", className)}
{...props}
/>
))
SidebarHeader.displayName = "SidebarHeader"
const SidebarFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("p-4 border-t border-border/40 mt-auto", className)}
{...props}
/>
))
SidebarFooter.displayName = "SidebarFooter"
const SidebarContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col flex-1 p-2", className)} {...props} />
))
SidebarContent.displayName = "SidebarContent"
const SidebarNav = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<nav
ref={ref}
className={cn("flex flex-col gap-1", className)}
{...props}
/>
))
SidebarNav.displayName = "SidebarNav"
const SidebarNavItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & { active?: boolean }
>(({ className, active, ...props }, ref) => (
<div
ref={ref}
className={cn(
"flex items-center px-3 py-2 rounded-md text-sm text-foreground/80 hover:text-foreground hover:bg-accent/50 transition-colors cursor-pointer",
active && "bg-accent/60 text-primary font-medium",
className
)}
{...props}
/>
))
SidebarNavItem.displayName = "SidebarNavItem"
const SidebarSection = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("mb-2", className)} {...props} />
))
SidebarSection.displayName = "SidebarSection"
const SidebarSectionTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-xs uppercase font-medium text-muted-foreground/70 tracking-wider px-3 py-1", className)}
{...props}
/>
))
SidebarSectionTitle.displayName = "SidebarSectionTitle"
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] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 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 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 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(
"duration-200 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] 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 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>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(
"absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
))
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("rounded-md h-8 flex gap-2 px-2 items-center", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 flex-1 max-w-[--skeleton-width]"
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 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 aria-disabled:pointer-events-none aria-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,
SidebarNav,
SidebarNavItem,
SidebarSection,
SidebarSectionTitle
}
+25
View File
@@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
interface SkeletonProps extends React.HTMLAttributes<HTMLDivElement> {
animated?: boolean
}
function Skeleton({
className,
animated = true,
...props
}: SkeletonProps) {
return (
<div
className={cn(
"rounded-md bg-muted/70",
animated && "animate-pulse",
className
)}
{...props}
/>
)
}
export { Skeleton }
+26
View File
@@ -0,0 +1,26 @@
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-1.5 w-full grow overflow-hidden rounded-full bg-secondary/50">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow-sm ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:border-primary hover:scale-110" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
export { Slider }
+31
View File
@@ -0,0 +1,31 @@
import React from "react"
import { Toaster as Sonner, toast } from "sonner"
import { useTheme } from "@/components/theme-provider"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme } = 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 }
+27
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-5 w-10 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-md ring-0 transition-transform duration-200 ease-in-out data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0.5 data-[state=checked]:bg-white"
)}
/>
</SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName
export { Switch }
+117
View File
@@ -0,0 +1,117 @@
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 hover:bg-muted/50 data-[state=selected]:bg-muted",
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,
}
+53
View File
@@ -0,0 +1,53 @@
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted/50 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 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-primary data-[state=active]:shadow-sm hover:text-foreground",
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-primary focus-visible:ring-offset-2 animate-in fade-in-0 data-[state=inactive]:animate-out data-[state=inactive]:fade-out-0 duration-200",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.TextareaHTMLAttributes<HTMLTextAreaElement>
>(({ 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/60 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary focus-visible:border-primary/50 disabled:cursor-not-allowed disabled:opacity-50 transition-colors resize-none",
className
)}
ref={ref}
{...props}
/>
)
})
Textarea.displayName = "Textarea"
export { Textarea }
+127
View File
@@ -0,0 +1,127 @@
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",
},
},
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 hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", 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,
}
+33
View File
@@ -0,0 +1,33 @@
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>
)
}
+67
View File
@@ -0,0 +1,67 @@
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> & {
orientation?: "horizontal" | "vertical"
}
>(({ className, variant, size, orientation = "horizontal", children, ...props }, ref) => (
<ToggleGroupPrimitive.Root
ref={ref}
className={cn(
"flex items-center gap-1",
orientation === "vertical" ? "flex-col" : "flex-row",
variant === "outline" && "bg-background rounded-md border border-input p-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,
}),
context.variant === "outline" && "data-[state=on]:bg-background data-[state=on]:text-foreground",
className
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
)
})
ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName
export { ToggleGroup, ToggleGroupItem }
+45
View File
@@ -0,0 +1,45 @@
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 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent/60 data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent hover:bg-muted/60 hover:text-foreground",
outline:
"border border-input bg-transparent hover:bg-accent/20 hover:text-accent-foreground data-[state=on]:border-accent",
soft:
"bg-transparent hover:bg-primary/10 data-[state=on]:bg-primary/20 data-[state=on]:text-primary",
},
size: {
default: "h-10 px-3",
sm: "h-8 px-2.5 text-xs",
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 }
+28
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 border-border/40 bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-lg 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 }
+3
View File
@@ -0,0 +1,3 @@
import { useToast, toast } from "@/hooks/use-toast";
export { useToast, toast };
+36
View File
@@ -0,0 +1,36 @@
import React, { createContext, useContext, useState } from 'react';
// import { v4 as uuidv4 } from 'uuid';
// import { toast } from '@/components/ui/use-toast';
interface AppContextType {
sidebarOpen: boolean;
toggleSidebar: () => void;
}
const defaultAppContext: AppContextType = {
sidebarOpen: false,
toggleSidebar: () => {},
};
const AppContext = createContext<AppContextType>(defaultAppContext);
export const useAppContext = () => useContext(AppContext);
export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [sidebarOpen, setSidebarOpen] = useState(false);
const toggleSidebar = () => {
setSidebarOpen(prev => !prev);
};
return (
<AppContext.Provider
value={{
sidebarOpen,
toggleSidebar,
}}
>
{children}
</AppContext.Provider>
);
};
+309
View File
@@ -0,0 +1,309 @@
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { supabase } from '@/lib/supabase';
import { User } from '@supabase/supabase-js';
import { isMobileApp, getNativeWalletAddress, getNativeAccountName } from '@/lib/mobile-bridge';
// Session timeout configuration
const SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
const ACTIVITY_CHECK_INTERVAL_MS = 60 * 1000; // Check every 1 minute
const LAST_ACTIVITY_KEY = 'last_activity_timestamp';
const REMEMBER_ME_KEY = 'remember_me';
interface AuthContextType {
user: User | null;
loading: boolean;
isAdmin: boolean;
signIn: (email: string, password: string, rememberMe?: boolean) => Promise<{ error: Error | null }>;
signUp: (email: string, password: string, username: string, referralCode?: string) => Promise<{ error: Error | null }>;
signOut: () => Promise<void>;
checkAdminStatus: () => Promise<boolean>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [isAdmin, setIsAdmin] = useState(false);
// ========================================
// SESSION TIMEOUT MANAGEMENT
// ========================================
// Update last activity timestamp
const updateLastActivity = useCallback(() => {
localStorage.setItem(LAST_ACTIVITY_KEY, Date.now().toString());
}, []);
const signOut = useCallback(async () => {
setIsAdmin(false);
setUser(null);
localStorage.removeItem(LAST_ACTIVITY_KEY);
localStorage.removeItem(REMEMBER_ME_KEY);
await supabase.auth.signOut();
}, []);
// Check if session has timed out
const checkSessionTimeout = useCallback(async () => {
if (!user) return;
// Skip timeout check if "Remember Me" is enabled
const rememberMe = localStorage.getItem(REMEMBER_ME_KEY);
if (rememberMe === 'true') {
return; // Don't timeout if user chose to be remembered
}
const lastActivity = localStorage.getItem(LAST_ACTIVITY_KEY);
if (!lastActivity) {
updateLastActivity();
return;
}
const lastActivityTime = parseInt(lastActivity, 10);
const now = Date.now();
const inactiveTime = now - lastActivityTime;
if (inactiveTime >= SESSION_TIMEOUT_MS) {
if (import.meta.env.DEV) console.log('⏱️ Session timeout - logging out due to inactivity');
await signOut();
}
}, [user, updateLastActivity, signOut]);
// Setup activity listeners
useEffect(() => {
if (!user) return;
// Update activity on user interactions
const activityEvents = ['mousedown', 'keydown', 'scroll', 'touchstart'];
const handleActivity = () => {
updateLastActivity();
};
// Register event listeners
activityEvents.forEach((event) => {
window.addEventListener(event, handleActivity);
});
// Initial activity timestamp
updateLastActivity();
// Check for timeout periodically
const timeoutChecker = setInterval(checkSessionTimeout, ACTIVITY_CHECK_INTERVAL_MS);
// Cleanup
return () => {
activityEvents.forEach((event) => {
window.removeEventListener(event, handleActivity);
});
clearInterval(timeoutChecker);
};
}, [user, updateLastActivity, checkSessionTimeout]);
const checkAdminStatus = useCallback(async () => {
// Admin wallet whitelist (blockchain-based auth)
const ADMIN_WALLETS = [
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', // Founder (original)
'5DFwqK698vL4gXHEcanaewnAqhxJ2rjhAogpSTHw3iwGDwd3', // Founder delegate (initial KYC member)
'5GgTgG9sRmPQAYU1RsTejZYnZRjwzKZKWD3awtuqjHioki45', // Founder (current dev wallet)
];
try {
// PRIMARY: Check wallet-based admin (blockchain auth)
const connectedWallet = localStorage.getItem('selectedWallet');
if (import.meta.env.DEV) console.log('🔍 Admin check - Connected wallet:', connectedWallet);
if (import.meta.env.DEV) console.log('🔍 Admin check - Whitelist:', ADMIN_WALLETS);
if (connectedWallet && ADMIN_WALLETS.includes(connectedWallet)) {
if (import.meta.env.DEV) console.log('✅ Admin access granted (wallet-based)');
setIsAdmin(true);
return true;
}
// SECONDARY: Check Supabase admin_roles (if wallet not in whitelist)
const { data: { user } } = await supabase.auth.getUser();
if (user) {
const { data, error } = await supabase
.from('admin_roles')
.select('role')
.eq('user_id', user.id)
.maybeSingle();
if (!error && data && ['admin', 'super_admin'].includes(data.role)) {
if (import.meta.env.DEV) console.log('✅ Admin access granted (Supabase-based)');
setIsAdmin(true);
return true;
}
}
if (import.meta.env.DEV) console.log('❌ Admin access denied');
setIsAdmin(false);
return false;
} catch (err) {
if (import.meta.env.DEV) console.error('Admin check error:', err);
setIsAdmin(false);
return false;
}
}, []);
// Setup native mobile wallet if running in mobile app
const setupMobileWallet = useCallback(() => {
if (isMobileApp()) {
const nativeAddress = getNativeWalletAddress();
const nativeAccountName = getNativeAccountName();
if (nativeAddress) {
// Store native wallet address for admin checks and wallet operations
localStorage.setItem('selectedWallet', nativeAddress);
if (nativeAccountName) {
localStorage.setItem('selectedWalletName', nativeAccountName);
}
if (import.meta.env.DEV) {
console.log('[Mobile] Native wallet detected:', nativeAddress);
}
// Dispatch wallet change event
window.dispatchEvent(new Event('walletChanged'));
}
}
}, []);
useEffect(() => {
// Setup mobile wallet first
setupMobileWallet();
// Check active sessions and sets the user
supabase.auth.getSession().then(({ data: { session } }) => {
setUser(session?.user ?? null);
checkAdminStatus(); // Check admin status regardless of Supabase session
setLoading(false);
}).catch(() => {
// If Supabase is not available, still check wallet-based admin
checkAdminStatus();
setLoading(false);
});
// Listen for changes on auth state
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user ?? null);
checkAdminStatus(); // Check admin status on auth change
setLoading(false);
});
// Listen for wallet changes (from PezkuwiContext or native bridge)
const handleWalletChange = () => {
checkAdminStatus();
};
window.addEventListener('walletChanged', handleWalletChange);
// Listen for native bridge ready event (mobile app)
const handleNativeReady = () => {
if (import.meta.env.DEV) {
console.log('[Mobile] Native bridge ready');
}
setupMobileWallet();
checkAdminStatus();
};
window.addEventListener('pezkuwi-native-ready', handleNativeReady);
return () => {
subscription.unsubscribe();
window.removeEventListener('walletChanged', handleWalletChange);
window.removeEventListener('pezkuwi-native-ready', handleNativeReady);
};
}, [checkAdminStatus, setupMobileWallet]);
const signIn = async (email: string, password: string, rememberMe: boolean = false) => {
try {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (!error && data.user) {
// Store remember me preference
if (rememberMe) {
localStorage.setItem(REMEMBER_ME_KEY, 'true');
} else {
localStorage.removeItem(REMEMBER_ME_KEY);
}
await checkAdminStatus();
}
return { error };
} catch {
return {
error: {
message: 'Authentication service unavailable. Please try again later.'
}
};
}
};
const signUp = async (email: string, password: string, username: string, referralCode?: string) => {
try {
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
username,
referral_code: referralCode || null,
},
},
});
if (!error && data.user) {
// Create profile in profiles table with referral code
await supabase.from('profiles').insert({
id: data.user.id,
username,
email,
referred_by: referralCode || null,
});
// If there&apos;s a referral code, track it
if (referralCode) {
// You can add logic here to reward the referrer
// For example, update their referral count or add rewards
if (import.meta.env.DEV) console.log(`User registered with referral code: ${referralCode}`);
}
}
return { error };
} catch {
return {
error: {
message: 'Registration service unavailable. Please try again later.'
}
};
}
};
return (
<AuthContext.Provider value={{
user,
loading,
isAdmin,
signIn,
signUp,
signOut,
checkAdminStatus
}}>
{children}
</AuthContext.Provider>
);
};
+98
View File
@@ -0,0 +1,98 @@
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { usePezkuwi } from '@/contexts/PezkuwiContext';
import { supabase } from '@/lib/supabase';
import { getAllTikiNFTDetails, generateCitizenNumber, type TikiNFTDetails } from '@pezkuwi/lib/tiki';
import { getKycStatus } from '@pezkuwi/lib/kyc';
interface DashboardData {
profile: Record<string, unknown> | null | null;
nftDetails: { citizenNFT: TikiNFTDetails | null; roleNFTs: TikiNFTDetails[]; totalNFTs: number };
kycStatus: string;
citizenNumber: string;
loading: boolean;
}
const DashboardContext = createContext<DashboardData | undefined>(undefined);
export function DashboardProvider({ children }: { children: ReactNode }) {
const { user } = useAuth();
const { api, isApiReady, selectedAccount } = usePezkuwi();
const [profile, setProfile] = useState<Record<string, unknown> | null>(null);
const [nftDetails, setNftDetails] = useState<{ citizenNFT: TikiNFTDetails | null; roleNFTs: TikiNFTDetails[]; totalNFTs: number }>({
citizenNFT: null,
roleNFTs: [],
totalNFTs: 0
});
const [kycStatus, setKycStatus] = useState<string>('NotStarted');
const [loading, setLoading] = useState(true);
const fetchProfile = useCallback(async () => {
if (!user) {
setLoading(false);
return;
}
try {
const { data, error } = await supabase
.from('profiles')
.select('*')
.eq('id', user.id)
.maybeSingle();
if (error) {
if (import.meta.env.DEV) console.warn('Profile fetch error (this is normal if Supabase is not configured):', error.message);
return;
}
setProfile(data);
} catch (error) {
if (import.meta.env.DEV) console.warn('Error fetching profile (this is normal if Supabase is not configured):', error);
} finally {
setLoading(false);
}
}, [user]);
const fetchScoresAndTikis = useCallback(async () => {
if (!selectedAccount || !api) return;
setLoading(true);
try {
const status = await getKycStatus(api, selectedAccount.address);
setKycStatus(status);
const details = await getAllTikiNFTDetails(api, selectedAccount.address);
setNftDetails(details);
} catch (error) {
if (import.meta.env.DEV) console.error('Error fetching data:', error);
} finally {
setLoading(false);
}
}, [selectedAccount, api]);
useEffect(() => {
fetchProfile();
if (selectedAccount && api && isApiReady) {
fetchScoresAndTikis();
}
}, [user, selectedAccount, api, isApiReady, fetchProfile, fetchScoresAndTikis]);
const citizenNumber = nftDetails.citizenNFT
? generateCitizenNumber(nftDetails.citizenNFT.owner, nftDetails.citizenNFT.collectionId, nftDetails.citizenNFT.itemId)
: 'N/A';
return (
<DashboardContext.Provider value={{ profile, nftDetails, kycStatus, citizenNumber, loading }}>
{children}
</DashboardContext.Provider>
);
}
export function useDashboard() {
const context = useContext(DashboardContext);
if (context === undefined) {
throw new Error('useDashboard must be used within a DashboardProvider');
}
return context;
}
+162
View File
@@ -0,0 +1,162 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import { useWallet } from './WalletContext';
import {
IdentityProfile,
KYCData,
Badge,
Role,
calculateReputationScore,
generateZKProof,
DEFAULT_BADGES,
ROLES
} from '@pezkuwi/lib/identity';
interface IdentityContextType {
profile: IdentityProfile | null;
isVerifying: boolean;
startKYC: (data: KYCData) => Promise<void>;
updatePrivacySettings: (settings: Record<string, boolean>) => void;
addBadge: (badge: Badge) => void;
assignRole: (role: Role) => void;
refreshReputation: () => void;
}
const IdentityContext = createContext<IdentityContextType | undefined>(undefined);
export function IdentityProvider({ children }: { children: React.ReactNode }) {
const { account } = useWallet();
const [profile, setProfile] = useState<IdentityProfile | null>(null);
const [isVerifying, setIsVerifying] = useState(false);
useEffect(() => {
if (account) {
// Load or create profile for connected wallet
const storedProfile = localStorage.getItem(`identity_${account}`);
if (storedProfile) {
setProfile(JSON.parse(storedProfile));
} else {
// Create new profile
const newProfile: IdentityProfile = {
address: account,
verificationLevel: 'none',
kycStatus: 'none',
reputationScore: 0,
badges: [],
roles: [],
privacySettings: {
showRealName: false,
showEmail: false,
showCountry: true,
useZKProof: true
}
};
setProfile(newProfile);
localStorage.setItem(`identity_${account}`, JSON.stringify(newProfile));
}
} else {
setProfile(null);
}
}, [account]);
const startKYC = async (data: KYCData) => {
if (!profile) return;
setIsVerifying(true);
try {
// Simulate KYC verification process
await new Promise(resolve => setTimeout(resolve, 3000));
// Generate ZK proof for privacy
generateZKProof(data);
const updatedProfile: IdentityProfile = {
...profile,
kycStatus: 'approved',
verificationLevel: data.documentType ? 'verified' : 'basic',
verificationDate: new Date(),
badges: [...profile.badges, ...DEFAULT_BADGES],
roles: [ROLES.verified_user as Role],
reputationScore: calculateReputationScore(
[],
data.documentType ? 'verified' : 'basic',
[...profile.badges, ...DEFAULT_BADGES]
)
};
setProfile(updatedProfile);
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
} catch (error) {
if (import.meta.env.DEV) console.error('KYC verification failed:', error);
} finally {
setIsVerifying(false);
}
};
const updatePrivacySettings = (settings: Record<string, boolean>) => {
if (!profile) return;
const updatedProfile = {
...profile,
privacySettings: { ...profile.privacySettings, ...settings }
};
setProfile(updatedProfile);
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
};
const addBadge = (badge: Badge) => {
if (!profile) return;
const updatedProfile = {
...profile,
badges: [...profile.badges, badge]
};
setProfile(updatedProfile);
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
};
const assignRole = (role: Role) => {
if (!profile) return;
const updatedProfile = {
...profile,
roles: [...profile.roles, role]
};
setProfile(updatedProfile);
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
};
const refreshReputation = () => {
if (!profile) return;
const newScore = calculateReputationScore([], profile.verificationLevel, profile.badges);
const updatedProfile = { ...profile, reputationScore: newScore };
setProfile(updatedProfile);
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
};
return (
<IdentityContext.Provider value={{
profile,
isVerifying,
startKYC,
updatePrivacySettings,
addBadge,
assignRole,
refreshReputation
}}>
{children}
</IdentityContext.Provider>
);
}
export const useIdentity = () => {
const context = useContext(IdentityContext);
if (!context) {
throw new Error('useIdentity must be used within IdentityProvider');
}
return context;
};
+330
View File
@@ -0,0 +1,330 @@
import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { ApiPromise, WsProvider } from '@pezkuwi/api';
import { web3Accounts, web3Enable } from '@pezkuwi/extension-dapp';
import type { InjectedAccountWithMeta } from '@pezkuwi/extension-inject/types';
import { DEFAULT_ENDPOINT } from '../../../shared/blockchain/pezkuwi';
import { isMobileApp, getNativeWalletAddress, getNativeAccountName } from '@/lib/mobile-bridge';
interface PezkuwiContextType {
api: ApiPromise | null;
isApiReady: boolean;
isConnected: boolean;
accounts: InjectedAccountWithMeta[];
selectedAccount: InjectedAccountWithMeta | null;
setSelectedAccount: (account: InjectedAccountWithMeta | null) => void;
connectWallet: () => Promise<void>;
disconnectWallet: () => void;
error: string | null;
sudoKey: string | null;
}
const PezkuwiContext = createContext<PezkuwiContextType | undefined>(undefined);
interface PezkuwiProviderProps {
children: ReactNode;
endpoint?: string;
}
export const PezkuwiProvider: React.FC<PezkuwiProviderProps> = ({
children,
endpoint = DEFAULT_ENDPOINT // Beta testnet RPC from shared config
}) => {
const [api, setApi] = useState<ApiPromise | null>(null);
const [isApiReady, setIsApiReady] = useState(false);
const [accounts, setAccounts] = useState<InjectedAccountWithMeta[]>([]);
const [selectedAccount, setSelectedAccount] = useState<InjectedAccountWithMeta | null>(null);
const [error, setError] = useState<string | null>(null);
const [sudoKey, setSudoKey] = useState<string | null>(null);
// Wrapper to trigger events when wallet changes
const handleSetSelectedAccount = (account: InjectedAccountWithMeta | null) => {
setSelectedAccount(account);
if (account) {
localStorage.setItem('selectedWallet', account.address);
if (import.meta.env.DEV) {
if (import.meta.env.DEV) console.log('💾 Wallet saved:', account.address);
}
window.dispatchEvent(new Event('walletChanged'));
} else {
localStorage.removeItem('selectedWallet');
window.dispatchEvent(new Event('walletChanged'));
}
};
// Initialize Pezkuwi API with fallback endpoints
useEffect(() => {
const FALLBACK_ENDPOINTS = [
endpoint,
import.meta.env.VITE_WS_ENDPOINT_FALLBACK_1,
import.meta.env.VITE_WS_ENDPOINT_FALLBACK_2,
].filter(Boolean);
const initApi = async () => {
let lastError: unknown = null;
for (const currentEndpoint of FALLBACK_ENDPOINTS) {
try {
if (import.meta.env.DEV) {
if (import.meta.env.DEV) console.log('🔗 Connecting to Pezkuwi node:', currentEndpoint);
}
const provider = new WsProvider(currentEndpoint);
const apiInstance = await ApiPromise.create({ provider });
await apiInstance.isReady;
setApi(apiInstance);
setIsApiReady(true);
setError(null);
if (import.meta.env.DEV) {
if (import.meta.env.DEV) console.log('✅ Connected to Pezkuwi node');
// Get chain info
const [chain, nodeName, nodeVersion] = await Promise.all([
apiInstance.rpc.system.chain(),
apiInstance.rpc.system.name(),
apiInstance.rpc.system.version(),
]);
if (import.meta.env.DEV) console.log(`📡 Chain: ${chain}`);
if (import.meta.env.DEV) console.log(`🖥️ Node: ${nodeName} v${nodeVersion}`);
}
// Fetch sudo key from blockchain
try {
const sudoAccount = await apiInstance.query.sudo.key();
const sudoAddress = sudoAccount.toString();
setSudoKey(sudoAddress);
if (import.meta.env.DEV) console.log(`🔑 Sudo key: ${sudoAddress}`);
} catch (err) {
if (import.meta.env.DEV) console.warn('⚠️ Failed to fetch sudo key (sudo pallet may not be available):', err);
}
return;
} catch (err) {
lastError = err;
if (import.meta.env.DEV) {
if (import.meta.env.DEV) console.warn(`⚠️ Failed to connect to ${currentEndpoint}, trying next...`);
}
continue;
}
}
if (import.meta.env.DEV) {
if (import.meta.env.DEV) console.error('❌ Failed to connect to all endpoints:', lastError);
}
setError('Failed to connect to blockchain network. Please try again later.');
setIsApiReady(false);
};
initApi();
return () => {
if (api) {
api.disconnect();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [endpoint]);
// Auto-restore wallet on page load (or setup mobile wallet)
useEffect(() => {
const restoreWallet = async () => {
// Check if running in mobile app
if (isMobileApp()) {
const nativeAddress = getNativeWalletAddress();
const nativeAccountName = getNativeAccountName();
if (nativeAddress) {
// Create a virtual account for the mobile wallet
const mobileAccount: InjectedAccountWithMeta = {
address: nativeAddress,
meta: {
name: nativeAccountName || 'Mobile Wallet',
source: 'pezkuwi-mobile',
},
type: 'sr25519',
};
setAccounts([mobileAccount]);
handleSetSelectedAccount(mobileAccount);
if (import.meta.env.DEV) {
console.log('[Mobile] Native wallet connected:', nativeAddress.slice(0, 8) + '...');
}
return;
}
}
// Desktop: Try to restore from localStorage
const savedAddress = localStorage.getItem('selectedWallet');
if (!savedAddress) return;
try {
// Enable extension
const extensions = await web3Enable('PezkuwiChain');
if (extensions.length === 0) return;
// Get accounts
const allAccounts = await web3Accounts();
if (allAccounts.length === 0) return;
// Find saved account
const savedAccount = allAccounts.find(acc => acc.address === savedAddress);
if (savedAccount) {
setAccounts(allAccounts);
handleSetSelectedAccount(savedAccount);
if (import.meta.env.DEV) {
console.log('✅ Wallet restored:', savedAddress.slice(0, 8) + '...');
}
}
} catch (err) {
if (import.meta.env.DEV) {
console.error('Failed to restore wallet:', err);
}
}
};
restoreWallet();
// Listen for native bridge ready event (mobile)
const handleNativeReady = () => {
if (import.meta.env.DEV) {
console.log('[Mobile] Native bridge ready, restoring wallet');
}
restoreWallet();
};
window.addEventListener('pezkuwi-native-ready', handleNativeReady);
return () => {
window.removeEventListener('pezkuwi-native-ready', handleNativeReady);
};
}, []);
// Connect wallet (Pezkuwi.js extension or native mobile)
const connectWallet = async () => {
try {
setError(null);
// Check if running in mobile app
if (isMobileApp()) {
const nativeAddress = getNativeWalletAddress();
const nativeAccountName = getNativeAccountName();
if (nativeAddress) {
// Create a virtual account for the mobile wallet
const mobileAccount: InjectedAccountWithMeta = {
address: nativeAddress,
meta: {
name: nativeAccountName || 'Mobile Wallet',
source: 'pezkuwi-mobile',
},
type: 'sr25519',
};
setAccounts([mobileAccount]);
handleSetSelectedAccount(mobileAccount);
if (import.meta.env.DEV) {
console.log('[Mobile] Native wallet connected:', nativeAddress.slice(0, 8) + '...');
}
return;
} else {
// Request wallet connection from native app
setError('Please connect your wallet in the app');
return;
}
}
// Desktop: Check if extension is installed first
const hasExtension = !!(window as unknown as { injectedWeb3?: Record<string, unknown> }).injectedWeb3;
// Enable extension
const extensions = await web3Enable('PezkuwiChain');
if (extensions.length === 0) {
if (hasExtension) {
// Extension is installed but user didn't authorize - don't redirect
setError('Please authorize the connection in your Pezkuwi Wallet extension');
} else {
// Extension not installed - show install link
setError('Pezkuwi Wallet extension not found. Please install from Chrome Web Store.');
window.open('https://chrome.google.com/webstore/detail/pezkuwi-wallet/fbnboicjjeebjhgnapneaeccpgjcdibn', '_blank');
}
return;
}
if (import.meta.env.DEV) {
console.log('✅ Pezkuwi.js extension enabled');
}
// Get accounts
const allAccounts = await web3Accounts();
if (allAccounts.length === 0) {
setError('No accounts found. Please create an account in Pezkuwi.js extension');
return;
}
setAccounts(allAccounts);
// Try to restore previously selected account, otherwise use first
const savedAddress = localStorage.getItem('selectedWallet');
const accountToSelect = savedAddress
? allAccounts.find(acc => acc.address === savedAddress) || allAccounts[0]
: allAccounts[0];
// Use wrapper to trigger events
handleSetSelectedAccount(accountToSelect);
if (import.meta.env.DEV) {
console.log(`✅ Found ${allAccounts.length} account(s)`);
}
} catch (err) {
if (import.meta.env.DEV) {
console.error('❌ Wallet connection failed:', err);
}
setError('Failed to connect wallet');
}
};
// Disconnect wallet
const disconnectWallet = () => {
setAccounts([]);
handleSetSelectedAccount(null);
if (import.meta.env.DEV) {
if (import.meta.env.DEV) console.log('🔌 Wallet disconnected');
}
};
const value: PezkuwiContextType = {
api,
isApiReady,
isConnected: isApiReady, // Alias for backward compatibility
accounts,
selectedAccount,
setSelectedAccount: handleSetSelectedAccount,
connectWallet,
disconnectWallet,
error,
sudoKey,
};
return (
<PezkuwiContext.Provider value={value}>
{children}
</PezkuwiContext.Provider>
);
};
// Hook to use Pezkuwi context
export const usePezkuwi = (): PezkuwiContextType => {
const context = useContext(PezkuwiContext);
if (!context) {
throw new Error('usePezkuwi must be used within PezkuwiProvider');
}
return context;
};
+177
View File
@@ -0,0 +1,177 @@
import { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react';
import { usePezkuwi } from '@/contexts/PezkuwiContext';
import { useWallet } from '@/contexts/WalletContext';
import { useToast } from '@/hooks/use-toast';
import {
getReferralStats,
getMyReferrals,
initiateReferral,
subscribeToReferralEvents,
type ReferralStats,
} from '@pezkuwi/lib/referral';
interface ReferralContextValue {
stats: ReferralStats | null;
myReferrals: string[];
loading: boolean;
inviteUser: (referredAddress: string) => Promise<boolean>;
refreshStats: () => Promise<void>;
}
const ReferralContext = createContext<ReferralContextValue | undefined>(undefined);
export function ReferralProvider({ children }: { children: ReactNode }) {
const { api, isApiReady } = usePezkuwi();
const { account } = useWallet();
const { toast } = useToast();
const [stats, setStats] = useState<ReferralStats | null>(null);
const [myReferrals, setMyReferrals] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
// Fetch referral statistics
const fetchStats = useCallback(async () => {
if (!api || !isApiReady || !account) {
setStats(null);
setMyReferrals([]);
setLoading(false);
return;
}
try {
setLoading(true);
const [fetchedStats, fetchedReferrals] = await Promise.all([
getReferralStats(api, account),
getMyReferrals(api, account),
]);
setStats(fetchedStats);
setMyReferrals(fetchedReferrals);
} catch (error) {
if (import.meta.env.DEV) console.error('Error fetching referral stats:', error);
toast({
title: 'Error',
description: 'Failed to load referral statistics',
variant: 'destructive',
});
} finally {
setLoading(false);
}
}, [api, isApiReady, account, toast]);
// Initial fetch
useEffect(() => {
fetchStats();
}, [fetchStats]);
// Subscribe to referral events for real-time updates
useEffect(() => {
if (!api || !isApiReady || !account) return;
let unsub: (() => void) | undefined;
subscribeToReferralEvents(api, (event) => {
// If this user is involved in the event, refresh stats
if (event.referrer === account || event.referred === account) {
if (event.type === 'initiated') {
toast({
title: 'Referral Sent',
description: `Invitation sent to ${event.referred.slice(0, 8)}...`,
});
} else if (event.type === 'confirmed') {
toast({
title: 'Referral Confirmed!',
description: `Your referral completed KYC. Total: ${event.count}`,
variant: 'default',
});
}
fetchStats();
}
}).then((unsubFn) => {
unsub = unsubFn;
});
return () => {
if (unsub) unsub();
};
}, [api, isApiReady, account, toast, fetchStats]);
// Invite a new user
const inviteUser = async (referredAddress: string): Promise<boolean> => {
if (!api || !account) {
toast({
title: 'Error',
description: 'Wallet not connected',
variant: 'destructive',
});
return false;
}
try {
// Validate address format
if (!referredAddress || referredAddress.length < 47) {
toast({
title: 'Invalid Address',
description: 'Please enter a valid Pezkuwi address',
variant: 'destructive',
});
return false;
}
toast({
title: 'Sending Invitation',
description: 'Please sign the transaction...',
});
await initiateReferral(api, { address: account, meta: { source: 'pezkuwi' } } as Record<string, unknown>, referredAddress);
toast({
title: 'Success!',
description: 'Referral invitation sent successfully',
});
// Refresh stats after successful invitation
await fetchStats();
return true;
} catch (error) {
if (import.meta.env.DEV) console.error('Error inviting user:', error);
let errorMessage = 'Failed to send referral invitation';
if (error.message) {
if (error.message.includes('SelfReferral')) {
errorMessage = 'You cannot refer yourself';
} else if (error.message.includes('AlreadyReferred')) {
errorMessage = 'This user has already been referred';
} else {
errorMessage = error.message;
}
}
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
});
return false;
}
};
const value: ReferralContextValue = {
stats,
myReferrals,
loading,
inviteUser,
refreshStats: fetchStats,
};
return <ReferralContext.Provider value={value}>{children}</ReferralContext.Provider>;
}
export function useReferral() {
const context = useContext(ReferralContext);
if (context === undefined) {
throw new Error('useReferral must be used within a ReferralProvider');
}
return context;
}
+327
View File
@@ -0,0 +1,327 @@
// ========================================
// WalletContext - Pezkuwi.js Wallet Integration
// ========================================
// This context wraps PezkuwiContext and provides wallet functionality
// ⚠️ MIGRATION NOTE: This now uses Pezkuwi.js instead of MetaMask/Ethereum
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { usePezkuwi } from './PezkuwiContext';
import { WALLET_ERRORS, formatBalance, ASSET_IDS } from '@pezkuwi/lib/wallet';
import type { InjectedAccountWithMeta } from '@pezkuwi/extension-inject/types';
import type { Signer } from '@pezkuwi/api/types';
import { web3FromAddress } from '@pezkuwi/extension-dapp';
import { isMobileApp, signTransactionNative, type TransactionPayload } from '@/lib/mobile-bridge';
interface TokenBalances {
HEZ: string;
PEZ: string;
wHEZ: string;
USDT: string; // User-facing key for wUSDT (backend uses wUSDT asset ID 2)
}
interface WalletContextType {
isConnected: boolean;
account: string | null; // Current selected account address
accounts: InjectedAccountWithMeta[];
balance: string; // Legacy: HEZ balance
balances: TokenBalances; // All token balances
error: string | null;
signer: Signer | null; // Pezkuwi.js signer for transactions
connectWallet: () => Promise<void>;
disconnect: () => void;
switchAccount: (account: InjectedAccountWithMeta) => void;
signTransaction: (tx: unknown) => Promise<string>;
signMessage: (message: string) => Promise<string>;
refreshBalances: () => Promise<void>; // Refresh all token balances
}
const WalletContext = createContext<WalletContextType | undefined>(undefined);
export const WalletProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const pezkuwi = usePezkuwi();
if (import.meta.env.DEV) console.log('🎯 WalletProvider render:', {
hasApi: !!pezkuwi.api,
isApiReady: pezkuwi.isApiReady,
selectedAccount: pezkuwi.selectedAccount?.address,
accountsCount: pezkuwi.accounts.length
});
const [balance, setBalance] = useState<string>('0');
const [balances, setBalances] = useState<TokenBalances>({ HEZ: '0', PEZ: '0', wHEZ: '0', USDT: '0' });
const [error, setError] = useState<string | null>(null);
const [signer, setSigner] = useState<Signer | null>(null);
// Fetch all token balances when account changes
const updateBalance = useCallback(async (address: string) => {
if (!pezkuwi.api || !pezkuwi.isApiReady) {
if (import.meta.env.DEV) console.warn('API not ready, cannot fetch balance');
return;
}
try {
if (import.meta.env.DEV) console.log('💰 Fetching all token balances for:', address);
// Fetch HEZ (native token)
const { data: nativeBalance } = await pezkuwi.api.query.system.account(address);
const hezBalance = formatBalance(nativeBalance.free.toString());
setBalance(hezBalance); // Legacy support
// Fetch PEZ (Asset ID: 1)
let pezBalance = '0';
try {
const pezData = await pezkuwi.api.query.assets.account(ASSET_IDS.PEZ, address);
if (import.meta.env.DEV) console.log('📊 Raw PEZ data:', pezData.toHuman());
if (pezData.isSome) {
const assetData = pezData.unwrap();
const pezAmount = assetData.balance.toString();
pezBalance = formatBalance(pezAmount);
if (import.meta.env.DEV) console.log('✅ PEZ balance found:', pezBalance);
} else {
if (import.meta.env.DEV) console.warn('⚠️ PEZ asset not found for this account');
}
} catch (err) {
if (import.meta.env.DEV) console.error('❌ Failed to fetch PEZ balance:', err);
}
// Fetch wHEZ (Asset ID: 0)
let whezBalance = '0';
try {
const whezData = await pezkuwi.api.query.assets.account(ASSET_IDS.WHEZ, address);
if (import.meta.env.DEV) console.log('📊 Raw wHEZ data:', whezData.toHuman());
if (whezData.isSome) {
const assetData = whezData.unwrap();
const whezAmount = assetData.balance.toString();
whezBalance = formatBalance(whezAmount);
if (import.meta.env.DEV) console.log('✅ wHEZ balance found:', whezBalance);
} else {
if (import.meta.env.DEV) console.warn('⚠️ wHEZ asset not found for this account');
}
} catch (err) {
if (import.meta.env.DEV) console.error('❌ Failed to fetch wHEZ balance:', err);
}
// Fetch wUSDT (Asset ID: 2) - IMPORTANT: wUSDT has 6 decimals, not 12!
let wusdtBalance = '0';
try {
const wusdtData = await pezkuwi.api.query.assets.account(ASSET_IDS.WUSDT, address);
if (import.meta.env.DEV) console.log('📊 Raw wUSDT data:', wusdtData.toHuman());
if (wusdtData.isSome) {
const assetData = wusdtData.unwrap();
const wusdtAmount = assetData.balance.toString();
wusdtBalance = formatBalance(wusdtAmount, 6); // wUSDT uses 6 decimals!
if (import.meta.env.DEV) console.log('✅ wUSDT balance found:', wusdtBalance);
} else {
if (import.meta.env.DEV) console.warn('⚠️ wUSDT asset not found for this account');
}
} catch (err) {
if (import.meta.env.DEV) console.error('❌ Failed to fetch wUSDT balance:', err);
}
setBalances({
HEZ: hezBalance,
PEZ: pezBalance,
wHEZ: whezBalance,
USDT: wusdtBalance,
});
if (import.meta.env.DEV) console.log('✅ Balances updated:', { HEZ: hezBalance, PEZ: pezBalance, wHEZ: whezBalance, wUSDT: wusdtBalance });
} catch (err) {
if (import.meta.env.DEV) console.error('Failed to fetch balances:', err);
setError('Failed to fetch balances');
}
}, [pezkuwi.api, pezkuwi.isApiReady]);
// Connect wallet (Pezkuwi.js extension)
const connectWallet = useCallback(async () => {
try {
setError(null);
await pezkuwi.connectWallet();
} catch (err) {
if (import.meta.env.DEV) console.error('Wallet connection failed:', err);
const errorMessage = err instanceof Error ? err.message : WALLET_ERRORS.CONNECTION_FAILED;
setError(errorMessage);
}
}, [pezkuwi]);
// Disconnect wallet
const disconnect = useCallback(() => {
pezkuwi.disconnectWallet();
setBalance('0');
setError(null);
}, [pezkuwi]);
// Switch account
const switchAccount = useCallback((account: InjectedAccountWithMeta) => {
pezkuwi.setSelectedAccount(account);
}, [pezkuwi]);
// Sign and submit transaction
const signTransaction = useCallback(async (tx: unknown): Promise<string> => {
if (!pezkuwi.api || !pezkuwi.selectedAccount) {
throw new Error(WALLET_ERRORS.API_NOT_READY);
}
try {
// Check if running in mobile app - use native bridge for signing
if (isMobileApp()) {
if (import.meta.env.DEV) console.log('[Mobile] Using native bridge for transaction signing');
// Extract transaction details from the tx object
const txAny = tx as {
method: {
section: string;
method: string;
args: unknown[];
toHuman?: () => { args?: Record<string, unknown> };
};
};
// Get section, method and args from the transaction
const section = txAny.method.section;
const method = txAny.method.method;
// Extract args - convert to array format
const argsHuman = txAny.method.toHuman?.()?.args || {};
const args = Object.values(argsHuman);
if (import.meta.env.DEV) {
console.log('[Mobile] Transaction details:', { section, method, args });
}
const payload: TransactionPayload = { section, method, args };
// Sign and send via native bridge
const blockHash = await signTransactionNative(payload);
if (import.meta.env.DEV) {
console.log('[Mobile] Transaction submitted, block hash:', blockHash);
}
return blockHash;
}
// Desktop: Use browser extension for signing
const { web3FromAddress } = await import('@pezkuwi/extension-dapp');
const injector = await web3FromAddress(pezkuwi.selectedAccount.address);
// Sign and send transaction
const hash = await (tx as { signAndSend: (address: string, options: { signer: unknown }) => Promise<{ toHex: () => string }> }).signAndSend(
pezkuwi.selectedAccount.address,
{ signer: injector.signer }
);
return hash.toHex();
} catch (error) {
if (import.meta.env.DEV) console.error('Transaction failed:', error);
throw new Error(error instanceof Error ? error.message : WALLET_ERRORS.TRANSACTION_FAILED);
}
}, [pezkuwi.api, pezkuwi.selectedAccount]);
// Sign message
const signMessage = useCallback(async (message: string): Promise<string> => {
if (!pezkuwi.selectedAccount) {
throw new Error('No account selected');
}
try {
const { web3FromAddress } = await import('@pezkuwi/extension-dapp');
const injector = await web3FromAddress(pezkuwi.selectedAccount.address);
if (!injector.signer.signRaw) {
throw new Error('Wallet does not support message signing');
}
const { signature } = await injector.signer.signRaw({
address: pezkuwi.selectedAccount.address,
data: message,
type: 'bytes'
});
return signature;
} catch (error) {
if (import.meta.env.DEV) console.error('Message signing failed:', error);
throw new Error(error instanceof Error ? error.message : 'Failed to sign message');
}
}, [pezkuwi.selectedAccount]);
// Get signer from extension when account changes
useEffect(() => {
const getSigner = async () => {
if (pezkuwi.selectedAccount) {
try {
const injector = await web3FromAddress(pezkuwi.selectedAccount.address);
setSigner(injector.signer);
if (import.meta.env.DEV) console.log('✅ Signer obtained for', pezkuwi.selectedAccount.address);
} catch (error) {
if (import.meta.env.DEV) console.error('Failed to get signer:', error);
setSigner(null);
}
} else {
setSigner(null);
}
};
getSigner();
}, [pezkuwi.selectedAccount]);
// Update balance when selected account changes
useEffect(() => {
if (import.meta.env.DEV) console.log('🔄 WalletContext useEffect triggered!', {
hasAccount: !!pezkuwi.selectedAccount,
isApiReady: pezkuwi.isApiReady,
address: pezkuwi.selectedAccount?.address
});
if (pezkuwi.selectedAccount && pezkuwi.isApiReady) {
updateBalance(pezkuwi.selectedAccount.address);
}
}, [pezkuwi.selectedAccount, pezkuwi.isApiReady, updateBalance]);
// Sync error state with PezkuwiContext
useEffect(() => {
if (pezkuwi.error) {
setError(pezkuwi.error);
}
}, [pezkuwi.error]);
// Refresh balances for current account
const refreshBalances = useCallback(async () => {
if (pezkuwi.selectedAccount) {
await updateBalance(pezkuwi.selectedAccount.address);
}
}, [pezkuwi.selectedAccount, updateBalance]);
const value: WalletContextType = {
isConnected: pezkuwi.accounts.length > 0,
account: pezkuwi.selectedAccount?.address || null,
accounts: pezkuwi.accounts,
balance,
balances,
error: error || pezkuwi.error,
signer,
connectWallet,
disconnect,
switchAccount,
signTransaction,
signMessage,
refreshBalances,
};
return (
<WalletContext.Provider value={value}>
{children}
</WalletContext.Provider>
);
};
export const useWallet = () => {
const context = useContext(WalletContext);
if (!context) {
throw new Error('useWallet must be used within WalletProvider');
}
return context;
};
+172
View File
@@ -0,0 +1,172 @@
import React, { createContext, useContext, useEffect, useState, useCallback, useRef } from 'react';
import { useToast } from '@/hooks/use-toast';
interface WebSocketMessage {
type: 'comment' | 'vote' | 'sentiment' | 'mention' | 'reply' | 'proposal_update';
data: Record<string, unknown>;
timestamp: number;
}
interface WebSocketContextType {
isConnected: boolean;
subscribe: (event: string, callback: (data: Record<string, unknown>) => void) => void;
unsubscribe: (event: string, callback: (data: Record<string, unknown>) => void) => void;
sendMessage: (message: WebSocketMessage) => void;
reconnect: () => void;
}
const WebSocketContext = createContext<WebSocketContextType | null>(null);
const ENDPOINTS = [
'ws://localhost:8082', // Local Vite dev server
'ws://127.0.0.1:9944', // Local development node (primary)
'ws://localhost:9944', // Local development node (alternative)
'wss://ws.pezkuwichain.io', // Production WebSocket (fallback)
];
export const useWebSocket = () => {
const context = useContext(WebSocketContext);
if (!context) {
throw new Error('useWebSocket must be used within WebSocketProvider');
}
return context;
};
export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [isConnected, setIsConnected] = useState(false);
const ws = useRef<WebSocket | null>(null);
const reconnectTimeout = useRef<NodeJS.Timeout>();
const eventListeners = useRef<Map<string, Set<(data: Record<string, unknown>) => void>>>(new Map());
const { toast } = useToast();
// Connection state management
const currentEndpoint = useRef<string>('');
const hasShownFinalError = useRef(false);
const connectionAttempts = useRef(0);
const connect = useCallback((endpointIndex: number = 0) => {
// If we've tried all endpoints, show error once and stop
if (endpointIndex >= ENDPOINTS.length) {
if (!hasShownFinalError.current) {
if (import.meta.env.DEV) console.error('❌ All WebSocket endpoints failed');
toast({
title: "Real-time Connection Unavailable",
description: "Could not connect to WebSocket server. Live updates will be disabled.",
variant: "destructive",
});
hasShownFinalError.current = true;
}
return;
}
try {
const wsUrl = ENDPOINTS[endpointIndex];
currentEndpoint.current = wsUrl;
if (import.meta.env.DEV) console.log(`🔌 Attempting WebSocket connection to: ${wsUrl}`);
ws.current = new WebSocket(wsUrl);
ws.current.onopen = () => {
setIsConnected(true);
connectionAttempts.current = 0;
hasShownFinalError.current = false;
if (import.meta.env.DEV) console.log(`✅ WebSocket connected to: ${wsUrl}`);
// Only show success toast for production endpoint
if (endpointIndex === 0) {
toast({
title: "Connected",
description: "Real-time updates enabled",
});
}
};
ws.current.onmessage = (event) => {
try {
const message: WebSocketMessage = JSON.parse(event.data);
const listeners = eventListeners.current.get(message.type);
if (listeners) {
listeners.forEach(callback => callback(message.data));
}
} catch (error) {
if (import.meta.env.DEV) console.error('Failed to parse WebSocket message:', error);
}
};
ws.current.onerror = (error) => {
if (import.meta.env.DEV) console.warn(`⚠️ WebSocket error on ${wsUrl}:`, error);
};
ws.current.onclose = () => {
setIsConnected(false);
if (import.meta.env.DEV) console.log(`🔌 WebSocket disconnected from: ${wsUrl}`);
// Try next endpoint after 2 seconds
reconnectTimeout.current = setTimeout(() => {
connectionAttempts.current++;
// If we've been connected before and lost connection, try same endpoint first
if (connectionAttempts.current < 3) {
connect(endpointIndex);
} else {
// Try next endpoint in the list
connect(endpointIndex + 1);
connectionAttempts.current = 0;
}
}, 2000);
};
} catch (error) {
if (import.meta.env.DEV) console.error(`❌ Failed to create WebSocket connection to ${ENDPOINTS[endpointIndex]}:`, error);
// Try next endpoint immediately
setTimeout(() => connect(endpointIndex + 1), 1000);
}
}, [toast]);
useEffect(() => {
connect(0); // Start with first endpoint
return () => {
if (reconnectTimeout.current) {
clearTimeout(reconnectTimeout.current);
}
if (ws.current) {
ws.current.close();
}
};
}, [connect]);
const subscribe = useCallback((event: string, callback: (data: Record<string, unknown>) => void) => {
if (!eventListeners.current.has(event)) {
eventListeners.current.set(event, new Set());
}
eventListeners.current.get(event)?.add(callback);
}, []);
const unsubscribe = useCallback((event: string, callback: (data: Record<string, unknown>) => void) => {
eventListeners.current.get(event)?.delete(callback);
}, []);
const sendMessage = useCallback((message: WebSocketMessage) => {
if (ws.current?.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify(message));
} else {
if (import.meta.env.DEV) console.warn('WebSocket is not connected - message queued');
}
}, []);
const reconnect = useCallback(() => {
if (ws.current) {
ws.current.close();
}
hasShownFinalError.current = false;
connectionAttempts.current = 0;
connect(0); // Start from first endpoint again
}, [connect]);
return (
<WebSocketContext.Provider value={{ isConnected, subscribe, unsubscribe, sendMessage, reconnect }}>
{children}
</WebSocketContext.Provider>
);
};
+123
View File
@@ -0,0 +1,123 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&family=JetBrains+Mono:wght@100..800&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
/* Kurdish color scheme - kesk u sor u zer */
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 148 100% 32%; /* Kurdish green */
--primary-foreground: 0 0% 98%;
--secondary: 358 84% 52%; /* Kurdish red */
--secondary-foreground: 0 0% 98%;
--muted: 52 100% 50%; /* Kurdish yellow muted */
--muted-foreground: 0 0% 20%;
--accent: 52 100% 50%; /* Kurdish yellow */
--accent-foreground: 0 0% 9%;
--destructive: 358 84% 52%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 148 100% 32%;
--radius: 0.5rem;
--chart-1: 148 100% 32%;
--chart-2: 358 84% 52%;
--chart-3: 52 100% 50%;
--chart-4: 148 100% 25%;
--chart-5: 358 84% 40%;
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 0 0% 3.9%;
--sidebar-primary: 148 100% 32%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 52 100% 50%;
--sidebar-accent-foreground: 0 0% 9%;
--sidebar-border: 0 0% 89.8%;
--sidebar-ring: 148 100% 32%;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 148 100% 40%; /* Kurdish green dark */
--primary-foreground: 0 0% 9%;
--secondary: 358 84% 60%; /* Kurdish red dark */
--secondary-foreground: 0 0% 9%;
--muted: 52 100% 30%; /* Kurdish yellow dark muted */
--muted-foreground: 0 0% 98%;
--accent: 52 100% 45%; /* Kurdish yellow dark */
--accent-foreground: 0 0% 9%;
--destructive: 358 84% 52%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 148 100% 40%;
--chart-1: 148 100% 40%;
--chart-2: 358 84% 60%;
--chart-3: 52 100% 45%;
--chart-4: 148 100% 30%;
--chart-5: 358 84% 50%;
--sidebar-background: 0 0% 7%;
--sidebar-foreground: 0 0% 98%;
--sidebar-primary: 148 100% 40%;
--sidebar-primary-foreground: 0 0% 9%;
--sidebar-accent: 52 100% 45%;
--sidebar-accent-foreground: 0 0% 9%;
--sidebar-border: 0 0% 14.9%;
--sidebar-ring: 148 100% 40%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground font-sans dark:bg-background dark:text-foreground;
}
pre, code {
@apply font-mono;
}
}
.markdown-editor {
@apply font-mono text-base leading-relaxed;
}
.markdown-preview {
@apply prose max-w-none prose-blue dark:prose-invert;
}
.markdown-preview pre {
@apply bg-secondary p-4 rounded-md overflow-x-auto;
}
.markdown-preview code {
@apply text-sm font-mono text-primary;
}
.markdown-preview h1,
.markdown-preview h2,
.markdown-preview h3,
.markdown-preview h4,
.markdown-preview h5,
.markdown-preview h6 {
@apply font-sans font-semibold text-foreground;
}
.markdown-preview ul,
.markdown-preview ol {
@apply my-4 ml-6;
}
+195
View File
@@ -0,0 +1,195 @@
/**
* Mobile Bridge Utility
*
* Handles communication between the web app and native mobile app (React Native WebView).
* When running inside the Pezkuwi mobile app, this bridge enables:
* - Native wallet integration (address, signing)
* - Platform detection
* - Native navigation
*/
// Type definitions for the native bridge
declare global {
interface Window {
PEZKUWI_MOBILE?: boolean;
PEZKUWI_PLATFORM?: 'ios' | 'android';
PEZKUWI_ADDRESS?: string;
PEZKUWI_ACCOUNT_NAME?: string;
ReactNativeWebView?: {
postMessage: (message: string) => void;
};
PezkuwiNativeBridge?: {
signTransaction: (payload: { section: string; method: string; args: unknown[] }, callback: (hash: string | null, error: string | null) => void) => void;
connectWallet: () => void;
goBack: () => void;
isWalletConnected: () => boolean;
getAddress: () => string | null;
};
}
}
export interface MobileBridgeState {
isMobile: boolean;
platform: 'ios' | 'android' | 'web';
walletAddress: string | null;
accountName: string | null;
isWalletConnected: boolean;
}
/**
* Check if running inside mobile WebView
*/
export function isMobileApp(): boolean {
return typeof window !== 'undefined' && window.PEZKUWI_MOBILE === true;
}
/**
* Get current platform
*/
export function getPlatform(): 'ios' | 'android' | 'web' {
if (!isMobileApp()) return 'web';
return window.PEZKUWI_PLATFORM || 'android';
}
/**
* Get native wallet address (if connected in mobile app)
*/
export function getNativeWalletAddress(): string | null {
if (!isMobileApp()) return null;
return window.PEZKUWI_ADDRESS || window.PezkuwiNativeBridge?.getAddress() || null;
}
/**
* Get native account name
*/
export function getNativeAccountName(): string | null {
if (!isMobileApp()) return null;
return window.PEZKUWI_ACCOUNT_NAME || null;
}
/**
* Check if native wallet is connected
*/
export function isNativeWalletConnected(): boolean {
if (!isMobileApp()) return false;
return window.PezkuwiNativeBridge?.isWalletConnected() || !!window.PEZKUWI_ADDRESS;
}
/**
* Request wallet connection from native app
*/
export function requestNativeWalletConnection(): void {
if (!isMobileApp()) return;
window.PezkuwiNativeBridge?.connectWallet();
}
export interface TransactionPayload {
section: string;
method: string;
args: unknown[];
}
/**
* Sign and submit transaction using native wallet
* Returns a promise that resolves with the block hash or rejects with error
*/
export function signTransactionNative(payload: TransactionPayload): Promise<string> {
return new Promise((resolve, reject) => {
if (!isMobileApp() || !window.PezkuwiNativeBridge) {
reject(new Error('Native bridge not available'));
return;
}
window.PezkuwiNativeBridge.signTransaction(payload, (hash, error) => {
if (error) {
reject(new Error(error));
} else if (hash) {
resolve(hash);
} else {
reject(new Error('No transaction hash returned'));
}
});
});
}
/**
* Legacy: Sign transaction using native wallet (raw hex - deprecated)
* @deprecated Use signTransactionNative with TransactionPayload instead
*/
export function signTransactionNativeHex(extrinsicHex: string): Promise<string> {
return new Promise((resolve, reject) => {
if (!isMobileApp() || !window.ReactNativeWebView) {
reject(new Error('Native bridge not available'));
return;
}
// For backwards compatibility, send as legacy format
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'SIGN_TRANSACTION_LEGACY',
payload: { extrinsicHex }
}));
// Note: This won't work without proper callback handling
reject(new Error('Legacy signing not supported - use TransactionPayload'));
});
}
/**
* Navigate back in native app
*/
export function navigateBackNative(): void {
if (!isMobileApp()) return;
window.PezkuwiNativeBridge?.goBack();
}
/**
* Send message to native app
*/
export function sendMessageToNative(type: string, payload?: unknown): void {
if (!isMobileApp() || !window.ReactNativeWebView) return;
window.ReactNativeWebView.postMessage(JSON.stringify({ type, payload }));
}
/**
* Get current mobile bridge state
*/
export function getMobileBridgeState(): MobileBridgeState {
const isMobile = isMobileApp();
return {
isMobile,
platform: getPlatform(),
walletAddress: getNativeWalletAddress(),
accountName: getNativeAccountName(),
isWalletConnected: isNativeWalletConnected(),
};
}
/**
* Log to native console (for debugging)
*/
export function logToNative(message: string, data?: unknown): void {
if (!isMobileApp()) {
console.log(message, data);
return;
}
sendMessageToNative('CONSOLE_LOG', { message, data });
}
// Export a singleton for easy access
export const mobileBridge = {
isMobileApp,
getPlatform,
getNativeWalletAddress,
getNativeAccountName,
isNativeWalletConnected,
requestNativeWalletConnection,
signTransactionNative,
navigateBackNative,
sendMessageToNative,
getMobileBridgeState,
logToNative,
};
export default mobileBridge;
+91
View File
@@ -0,0 +1,91 @@
import * as Sentry from '@sentry/react';
export const initSentry = () => {
const dsn = import.meta.env.VITE_SENTRY_DSN;
// Only initialize if DSN is provided and not in development
if (!dsn || import.meta.env.DEV) {
if (import.meta.env.DEV) {
console.log('📊 Sentry disabled in development');
}
return;
}
Sentry.init({
dsn,
environment: import.meta.env.VITE_SENTRY_ENVIRONMENT || 'production',
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({
maskAllText: false,
blockAllMedia: false,
}),
],
// Performance Monitoring
tracesSampleRate: parseFloat(import.meta.env.VITE_SENTRY_TRACES_SAMPLE_RATE || '0.1'),
// Session Replay
replaysSessionSampleRate: 0.1, // 10% of sessions
replaysOnErrorSampleRate: 1.0, // 100% of sessions with errors
// Filter out sensitive data
beforeSend(event) {
// Don't send errors in development
if (import.meta.env.DEV) {
return null;
}
// Filter out wallet addresses and sensitive data
if (event.request?.url) {
event.request.url = event.request.url.replace(/5[A-HJ-NP-Za-km-z]{47}/g, '[REDACTED_WALLET]');
}
if (event.breadcrumbs) {
event.breadcrumbs = event.breadcrumbs.map(breadcrumb => {
if (breadcrumb.data) {
breadcrumb.data = JSON.parse(
JSON.stringify(breadcrumb.data).replace(/5[A-HJ-NP-Za-km-z]{47}/g, '[REDACTED_WALLET]')
);
}
return breadcrumb;
});
}
return event;
},
// Ignore common non-critical errors
ignoreErrors: [
// Browser extensions (MetaMask, etc.)
'top.GLOBALS',
'canvas.contentDocument',
'MyApp_RemoveAllHighlights',
'atomicFindClose',
'ObjectMultiplex',
'StreamMiddleware',
'malformed chunk',
'Unknown response id',
// Network errors that are expected
'NetworkError',
'Failed to fetch',
'Load failed',
// Polkadot.js expected disconnections
'WebSocket is not connected',
'RPC connection closed',
],
});
// Set user context when available
const selectedWallet = localStorage.getItem('selectedWallet');
if (selectedWallet) {
Sentry.setUser({
id: selectedWallet.slice(0, 8), // Only first 8 chars for privacy
});
}
console.log('📊 Sentry initialized');
};
// Export Sentry for use in error boundaries and manual reporting
export { Sentry };
+13
View File
@@ -0,0 +1,13 @@
import { createClient } from '@supabase/supabase-js';
// Initialize Supabase client from environment variables
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseKey) {
if (import.meta.env.DEV) console.warn('Supabase credentials not found in environment variables');
}
const supabase = createClient(supabaseUrl, supabaseKey);
export { supabase };
+20
View File
@@ -0,0 +1,20 @@
import { expect, test, describe } from 'vitest';
import { cn } from './utils';
describe('cn', () => {
test('should merge Tailwind classes correctly', () => {
expect(cn('px-2', 'py-1', 'px-4')).toBe('py-1 px-4');
});
test('should handle conditional classes', () => {
expect(cn('text-red-500', false && 'text-blue-500', true && 'font-bold')).toBe('text-red-500 font-bold');
});
test('should handle empty inputs', () => {
expect(cn('', null, undefined)).toBe('');
});
test('should handle mixed inputs', () => {
expect(cn('bg-red-500', 'text-white', 'p-4', 'bg-blue-500')).toBe('text-white p-4 bg-blue-500');
});
});
+14
View File
@@ -0,0 +1,14 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
/**
* Web-specific className utility (uses Tailwind merge)
*/
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Re-export formatNumber from shared utils
*/
export { formatNumber } from '@pezkuwi/utils/format';
+9
View File
@@ -0,0 +1,9 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
);
+132
View File
@@ -0,0 +1,132 @@
import type { Config } from "tailwindcss";
import animate from "tailwindcss-animate";
import typography from "@tailwindcss/typography";
export default {
darkMode: ["class"],
content: [
"./pages/**/*.{ts,tsx}",
"./components/**/*.{ts,tsx}",
"./app/**/*.{ts,tsx}",
"./src/**/*.{ts,tsx}",
],
prefix: "",
theme: {
container: {
center: true,
padding: '2rem',
screens: {
'2xl': '1400px'
}
},
extend: {
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
// Kurdish colors (kesk u sor u zer)
kurdish: {
green: {
DEFAULT: '#00a550',
dark: '#008040',
light: '#00c060'
},
red: {
DEFAULT: '#ed1c24',
dark: '#c41018',
light: '#ff3030'
},
yellow: {
DEFAULT: '#ffed00',
dark: '#e6d400',
light: '#fff740'
}
},
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))'
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))'
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))'
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))'
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))'
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))'
},
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))'
},
sidebar: {
DEFAULT: 'hsl(var(--sidebar-background))',
foreground: 'hsl(var(--sidebar-foreground))',
primary: 'hsl(var(--sidebar-primary))',
'primary-foreground': 'hsl(var(--sidebar-primary-foreground))',
accent: 'hsl(var(--sidebar-accent))',
'accent-foreground': 'hsl(var(--sidebar-accent-foreground))',
border: 'hsl(var(--sidebar-border))',
ring: 'hsl(var(--sidebar-ring))'
}
},
fontFamily: {
mono: ['JetBrains Mono', 'monospace'],
sans: ['Inter', 'sans-serif'],
},
borderRadius: {
lg: 'calc(var(--radius) + 2px)',
md: 'var(--radius)',
sm: 'calc(var(--radius) - 2px)'
},
keyframes: {
'accordion-down': {
from: { height: '0' },
to: { height: 'var(--radix-accordion-content-height)' },
},
'accordion-up': {
from: { height: 'var(--radix-accordion-content-height)' },
to: { height: '0' },
},
'fade-in': {
from: { opacity: '0' },
to: { opacity: '1' },
},
'slide-in': {
from: { transform: 'translateY(10px)', opacity: '0' },
to: { transform: 'translateY(0)', opacity: '1' },
},
},
animation: {
'accordion-down': 'accordion-down 0.2s ease-out',
'accordion-up': 'accordion-up 0.2s ease-out',
'fade-in': 'fade-in 0.3s ease-out',
'slide-in': 'slide-in 0.3s ease-out',
},
typography: {
DEFAULT: {
css: {
maxWidth: 'none',
},
},
},
}
},
plugins: [
animate,
typography,
],
} satisfies Config;
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})