Compare commits
19 Commits
feature/is
...
459cc0eced
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
459cc0eced | ||
|
|
e94952ad20 | ||
| 90b39481d1 | |||
| e83874162f | |||
| ebae5a82db | |||
|
|
1b8d4519e6 | ||
|
|
defcf2af9c | ||
|
|
e062a3a84f | ||
|
|
73b7735074 | ||
| 57f0e7efe7 | |||
|
|
b3fc8079c6 | ||
|
|
6d8e7b3224 | ||
|
|
8bb80dac2e | ||
|
|
247f2205b8 | ||
|
|
e96289de03 | ||
| 6de32baefb | |||
| 215c64762f | |||
|
|
ad7ae17985 | ||
| 96ba4c2809 |
6
.claude/settings.local.json
Normal file
6
.claude/settings.local.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"enabledMcpjsonServers": [
|
||||||
|
"supabase"
|
||||||
|
],
|
||||||
|
"enableAllProjectMcpServers": true
|
||||||
|
}
|
||||||
21
.dockerignore
Normal file
21
.dockerignore
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
*.md
|
||||||
|
!DOCKER.md
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
coverage
|
||||||
|
.nyc_output
|
||||||
|
*.test.ts
|
||||||
|
*.test.tsx
|
||||||
|
*.spec.ts
|
||||||
|
*.spec.tsx
|
||||||
98
.env.example
Normal file
98
.env.example
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
# =====================================================
|
||||||
|
# DECKERR DOCKER CONFIGURATION
|
||||||
|
# =====================================================
|
||||||
|
# Copy this file to .env and configure your settings
|
||||||
|
#
|
||||||
|
# Two deployment modes available:
|
||||||
|
# 1. External Supabase: Use docker-compose.yml (simpler)
|
||||||
|
# 2. Self-hosted Supabase: Use docker-compose.selfhosted.yml (full stack)
|
||||||
|
# =====================================================
|
||||||
|
|
||||||
|
# =====================================================
|
||||||
|
# MODE 1: EXTERNAL SUPABASE (docker-compose.yml)
|
||||||
|
# =====================================================
|
||||||
|
# Use this if you have:
|
||||||
|
# - A Supabase cloud account (supabase.com)
|
||||||
|
# - A separately self-hosted Supabase instance
|
||||||
|
# - Access to a paid hosted Supabase service
|
||||||
|
|
||||||
|
# Your Supabase project URL
|
||||||
|
VITE_SUPABASE_URL=https://your-project.supabase.co
|
||||||
|
|
||||||
|
# Your Supabase anonymous/public key
|
||||||
|
VITE_SUPABASE_ANON_KEY=your-anon-key-here
|
||||||
|
|
||||||
|
# Port to run Deckerr on (default: 3000)
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
|
||||||
|
# =====================================================
|
||||||
|
# MODE 2: SELF-HOSTED SUPABASE (docker-compose.selfhosted.yml)
|
||||||
|
# =====================================================
|
||||||
|
# Use this to run everything locally, including Supabase
|
||||||
|
|
||||||
|
# --- Site Configuration ---
|
||||||
|
# Your domain or IP address (used for redirects)
|
||||||
|
SITE_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# External API URL (Kong gateway)
|
||||||
|
API_EXTERNAL_URL=http://localhost:8000
|
||||||
|
|
||||||
|
# --- Port Configuration ---
|
||||||
|
DECKERR_PORT=3000
|
||||||
|
KONG_HTTP_PORT=8000
|
||||||
|
KONG_HTTPS_PORT=8443
|
||||||
|
POSTGRES_PORT=5432
|
||||||
|
|
||||||
|
# --- Security Keys ---
|
||||||
|
# IMPORTANT: Generate secure random values for production!
|
||||||
|
# You can use: openssl rand -base64 32
|
||||||
|
|
||||||
|
# PostgreSQL password
|
||||||
|
POSTGRES_PASSWORD=your-super-secret-postgres-password
|
||||||
|
|
||||||
|
# JWT Secret (must be at least 32 characters)
|
||||||
|
# Generate with: openssl rand -base64 32
|
||||||
|
JWT_SECRET=your-super-secret-jwt-token-with-at-least-32-characters
|
||||||
|
|
||||||
|
# JWT Expiry in seconds (default: 3600 = 1 hour)
|
||||||
|
JWT_EXPIRY=3600
|
||||||
|
|
||||||
|
# Supabase Anonymous Key
|
||||||
|
# Generate at: https://supabase.com/docs/guides/self-hosting#api-keys
|
||||||
|
# Or use: npx @supabase/cli@latest gen key --type anon --jwt-secret "YOUR_JWT_SECRET"
|
||||||
|
ANON_KEY=your-anon-key
|
||||||
|
|
||||||
|
# Supabase Service Role Key (admin access)
|
||||||
|
# Generate at: https://supabase.com/docs/guides/self-hosting#api-keys
|
||||||
|
# Or use: npx @supabase/cli@latest gen key --type service_role --jwt-secret "YOUR_JWT_SECRET"
|
||||||
|
SERVICE_ROLE_KEY=your-service-role-key
|
||||||
|
|
||||||
|
# --- Email Configuration (Optional) ---
|
||||||
|
# Required for email verification and password reset
|
||||||
|
SMTP_HOST=smtp.example.com
|
||||||
|
SMTP_PORT=587
|
||||||
|
SMTP_USER=your-email@example.com
|
||||||
|
SMTP_PASS=your-email-password
|
||||||
|
SMTP_ADMIN_EMAIL=admin@example.com
|
||||||
|
SMTP_SENDER_NAME=Deckerr
|
||||||
|
|
||||||
|
# Enable email auto-confirm (set to true to skip email verification)
|
||||||
|
ENABLE_EMAIL_AUTOCONFIRM=true
|
||||||
|
|
||||||
|
# --- Feature Flags ---
|
||||||
|
# Disable new user signups
|
||||||
|
DISABLE_SIGNUP=false
|
||||||
|
|
||||||
|
# Enable email signup
|
||||||
|
ENABLE_EMAIL_SIGNUP=true
|
||||||
|
|
||||||
|
# Enable anonymous users
|
||||||
|
ENABLE_ANONYMOUS_USERS=false
|
||||||
|
|
||||||
|
# --- Advanced ---
|
||||||
|
# Additional redirect URLs (comma-separated)
|
||||||
|
ADDITIONAL_REDIRECT_URLS=
|
||||||
|
|
||||||
|
# PostgREST schemas
|
||||||
|
PGRST_DB_SCHEMAS=public,graphql_public
|
||||||
8
.mcp.json
Normal file
8
.mcp.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"supabase": {
|
||||||
|
"type": "http",
|
||||||
|
"url": "https://mcp.supabase.com/mcp?project_ref=yedghjrpyxhxesnbtbip"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
191
DOCKER.md
Normal file
191
DOCKER.md
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
# Deckerr Docker Deployment
|
||||||
|
|
||||||
|
Self-host Deckerr with two deployment options:
|
||||||
|
|
||||||
|
## Deployment Options
|
||||||
|
|
||||||
|
| Option | Use Case | Complexity |
|
||||||
|
|--------|----------|------------|
|
||||||
|
| **External Supabase** | Use hosted Supabase (cloud or paid) | Simple |
|
||||||
|
| **Self-hosted Supabase** | Run everything locally | Advanced |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Option 1: External Supabase (Recommended)
|
||||||
|
|
||||||
|
Use your own Supabase instance (cloud, paid hosted, or separately self-hosted).
|
||||||
|
|
||||||
|
### Quick Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Copy environment template
|
||||||
|
cp .env.example .env
|
||||||
|
|
||||||
|
# 2. Edit .env with your Supabase credentials
|
||||||
|
VITE_SUPABASE_URL=https://your-project.supabase.co
|
||||||
|
VITE_SUPABASE_ANON_KEY=your-anon-key
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# 3. Run database migrations on your Supabase
|
||||||
|
# Go to Supabase Dashboard > SQL Editor and run:
|
||||||
|
# Contents of supabase/migrations/20250131132458_black_frost.sql
|
||||||
|
|
||||||
|
# 4. Start Deckerr
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# 5. Access at http://localhost:3000
|
||||||
|
```
|
||||||
|
|
||||||
|
### Using Hosted Supabase (Paid Service)
|
||||||
|
|
||||||
|
Contact the Deckerr team for access credentials to use the hosted backend.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Option 2: Self-Hosted Supabase (Full Stack)
|
||||||
|
|
||||||
|
Run Deckerr with a complete self-hosted Supabase stack.
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Docker & Docker Compose
|
||||||
|
- 2GB+ RAM
|
||||||
|
- Ports: 3000, 5432, 8000
|
||||||
|
|
||||||
|
### Quick Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Copy environment template
|
||||||
|
cp .env.example .env
|
||||||
|
|
||||||
|
# 2. Generate secure keys
|
||||||
|
# JWT Secret (required)
|
||||||
|
openssl rand -base64 32
|
||||||
|
|
||||||
|
# Generate Supabase API keys
|
||||||
|
# Option A: Use online generator at https://supabase.com/docs/guides/self-hosting#api-keys
|
||||||
|
# Option B: Use Supabase CLI
|
||||||
|
npx @supabase/cli@latest gen key --type anon --jwt-secret "YOUR_JWT_SECRET"
|
||||||
|
npx @supabase/cli@latest gen key --type service_role --jwt-secret "YOUR_JWT_SECRET"
|
||||||
|
|
||||||
|
# 3. Update .env with your generated values
|
||||||
|
POSTGRES_PASSWORD=<generated-password>
|
||||||
|
JWT_SECRET=<generated-jwt-secret>
|
||||||
|
ANON_KEY=<generated-anon-key>
|
||||||
|
SERVICE_ROLE_KEY=<generated-service-key>
|
||||||
|
|
||||||
|
# 4. Start all services
|
||||||
|
docker-compose -f docker-compose.selfhosted.yml up -d
|
||||||
|
|
||||||
|
# 5. Access Deckerr at http://localhost:3000
|
||||||
|
# API available at http://localhost:8000
|
||||||
|
```
|
||||||
|
|
||||||
|
### Generate Keys Script
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
JWT_SECRET=$(openssl rand -base64 32)
|
||||||
|
echo "JWT_SECRET=$JWT_SECRET"
|
||||||
|
echo ""
|
||||||
|
echo "Now generate API keys at:"
|
||||||
|
echo "https://supabase.com/docs/guides/self-hosting#api-keys"
|
||||||
|
echo "Use this JWT secret: $JWT_SECRET"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Self-Hosted Services
|
||||||
|
|
||||||
|
| Service | Port | Description |
|
||||||
|
|---------|------|-------------|
|
||||||
|
| Deckerr | 3000 | Frontend app |
|
||||||
|
| Kong | 8000 | API Gateway |
|
||||||
|
| PostgreSQL | 5432 | Database |
|
||||||
|
| Auth | 9999 | Authentication (internal) |
|
||||||
|
| REST | 3000 | PostgREST API (internal) |
|
||||||
|
| Realtime | 4000 | WebSocket (internal) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
### External Supabase Mode
|
||||||
|
|
||||||
|
| Variable | Required | Description |
|
||||||
|
|----------|----------|-------------|
|
||||||
|
| `VITE_SUPABASE_URL` | Yes | Supabase project URL |
|
||||||
|
| `VITE_SUPABASE_ANON_KEY` | Yes | Supabase anonymous key |
|
||||||
|
| `PORT` | No | App port (default: 3000) |
|
||||||
|
|
||||||
|
### Self-Hosted Mode
|
||||||
|
|
||||||
|
| Variable | Required | Description |
|
||||||
|
|----------|----------|-------------|
|
||||||
|
| `POSTGRES_PASSWORD` | Yes | PostgreSQL password |
|
||||||
|
| `JWT_SECRET` | Yes | JWT signing secret (32+ chars) |
|
||||||
|
| `ANON_KEY` | Yes | Supabase anonymous key |
|
||||||
|
| `SERVICE_ROLE_KEY` | Yes | Supabase service role key |
|
||||||
|
| `SITE_URL` | No | Your domain (default: localhost) |
|
||||||
|
| `SMTP_*` | No | Email configuration |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Start (external Supabase)
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Start (self-hosted)
|
||||||
|
docker-compose -f docker-compose.selfhosted.yml up -d
|
||||||
|
|
||||||
|
# Stop
|
||||||
|
docker-compose down
|
||||||
|
|
||||||
|
# View logs
|
||||||
|
docker-compose logs -f
|
||||||
|
|
||||||
|
# Rebuild after code changes
|
||||||
|
docker-compose build --no-cache
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Reset database (self-hosted only)
|
||||||
|
docker-compose -f docker-compose.selfhosted.yml down -v
|
||||||
|
docker-compose -f docker-compose.selfhosted.yml up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Production Checklist
|
||||||
|
|
||||||
|
- [ ] Use strong passwords (generate with `openssl rand -base64 32`)
|
||||||
|
- [ ] Configure HTTPS with reverse proxy (nginx, Traefik, Caddy)
|
||||||
|
- [ ] Set up email (SMTP) for password reset
|
||||||
|
- [ ] Configure firewall rules
|
||||||
|
- [ ] Set up backups for PostgreSQL volume
|
||||||
|
- [ ] Consider rate limiting at reverse proxy level
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Container won't start
|
||||||
|
```bash
|
||||||
|
docker-compose logs <service-name>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database connection issues
|
||||||
|
```bash
|
||||||
|
# Check if database is healthy
|
||||||
|
docker-compose exec db pg_isready -U postgres
|
||||||
|
```
|
||||||
|
|
||||||
|
### Reset everything
|
||||||
|
```bash
|
||||||
|
docker-compose down -v
|
||||||
|
docker-compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Check service health
|
||||||
|
```bash
|
||||||
|
docker-compose ps
|
||||||
|
```
|
||||||
39
Dockerfile
Normal file
39
Dockerfile
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# Build stage
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Build arguments for Supabase configuration
|
||||||
|
ARG VITE_SUPABASE_URL
|
||||||
|
ARG VITE_SUPABASE_ANON_KEY
|
||||||
|
|
||||||
|
# Set environment variables for build
|
||||||
|
ENV VITE_SUPABASE_URL=$VITE_SUPABASE_URL
|
||||||
|
ENV VITE_SUPABASE_ANON_KEY=$VITE_SUPABASE_ANON_KEY
|
||||||
|
|
||||||
|
# Build the application
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Production stage
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
# Copy custom nginx config
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Copy built assets from builder
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
# Expose port 80
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
# Start nginx
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
157
PROJECT_STRUCTURE.md
Normal file
157
PROJECT_STRUCTURE.md
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
# Deckerr
|
||||||
|
|
||||||
|
A modern Magic: The Gathering deck builder and collection manager built with React, TypeScript, and Supabase.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Deckerr is a web application that allows Magic: The Gathering players to build and manage their decks, track their card collections, search for cards, and use a life counter during games. The application provides a clean, animated interface with user authentication and persistent storage.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Deck Management**: Create, edit, and organize your Magic: The Gathering decks
|
||||||
|
- **Collection Tracking**: Keep track of your card collection with quantity management
|
||||||
|
- **Card Search**: Search and browse Magic cards to add to your decks or collection
|
||||||
|
- **Life Counter**: Track player life totals during games
|
||||||
|
- **User Profiles**: Personalized user profiles with theme customization
|
||||||
|
- **Authentication**: Secure user authentication powered by Supabase
|
||||||
|
- **Format Support**: Support for different Magic formats (Commander, Standard, etc.)
|
||||||
|
|
||||||
|
## Technology Stack
|
||||||
|
|
||||||
|
- **Frontend**: React 18 with TypeScript
|
||||||
|
- **Build Tool**: Vite
|
||||||
|
- **Styling**: Tailwind CSS with custom animations
|
||||||
|
- **Backend/Database**: Supabase (PostgreSQL)
|
||||||
|
- **Authentication**: Supabase Auth
|
||||||
|
- **Icons**: Lucide React
|
||||||
|
- **Linting**: ESLint with TypeScript support
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
deckerr/
|
||||||
|
├── src/
|
||||||
|
│ ├── components/ # React components
|
||||||
|
│ │ ├── CardCarousel.tsx # Card carousel display
|
||||||
|
│ │ ├── CardSearch.tsx # Card search interface
|
||||||
|
│ │ ├── Collection.tsx # Collection management
|
||||||
|
│ │ ├── DeckBuilder.tsx # Deck building interface
|
||||||
|
│ │ ├── DeckCard.tsx # Deck card component
|
||||||
|
│ │ ├── DeckEditor.tsx # Deck editing interface
|
||||||
|
│ │ ├── DeckList.tsx # List of user decks
|
||||||
|
│ │ ├── DeckManager.tsx # Deck management
|
||||||
|
│ │ ├── LifeCounter.tsx # Game life counter
|
||||||
|
│ │ ├── LoginForm.tsx # User authentication form
|
||||||
|
│ │ ├── MagicCard.tsx # Magic card display component
|
||||||
|
│ │ ├── ManaIcons.tsx # Mana symbol icons
|
||||||
|
│ │ ├── Navigation.tsx # App navigation
|
||||||
|
│ │ └── Profile.tsx # User profile page
|
||||||
|
│ │
|
||||||
|
│ ├── contexts/ # React contexts
|
||||||
|
│ │ └── AuthContext.tsx # Authentication context
|
||||||
|
│ │
|
||||||
|
│ ├── lib/ # Library code
|
||||||
|
│ │ ├── Entities.ts # Supabase database types
|
||||||
|
│ │ └── supabase.ts # Supabase client configuration
|
||||||
|
│ │
|
||||||
|
│ ├── services/ # API and service layers
|
||||||
|
│ │ └── api.ts # API service functions
|
||||||
|
│ │
|
||||||
|
│ ├── types/ # TypeScript type definitions
|
||||||
|
│ │ └── index.ts # Shared types
|
||||||
|
│ │
|
||||||
|
│ ├── utils/ # Utility functions
|
||||||
|
│ │ ├── deckValidation.ts # Deck validation logic
|
||||||
|
│ │ └── theme.ts # Theme utilities
|
||||||
|
│ │
|
||||||
|
│ ├── App.tsx # Main application component
|
||||||
|
│ ├── main.tsx # Application entry point
|
||||||
|
│ ├── main.js # JavaScript entry
|
||||||
|
│ ├── index.css # Global styles
|
||||||
|
│ └── vite-env.d.ts # Vite type definitions
|
||||||
|
│
|
||||||
|
├── public/ # Static assets (if any)
|
||||||
|
│
|
||||||
|
├── index.html # HTML entry point
|
||||||
|
├── package.json # Project dependencies
|
||||||
|
├── vite.config.ts # Vite configuration
|
||||||
|
├── tsconfig.json # TypeScript configuration
|
||||||
|
├── tsconfig.app.json # App-specific TS config
|
||||||
|
├── tsconfig.node.json # Node-specific TS config
|
||||||
|
├── tailwind.config.js # Tailwind CSS configuration
|
||||||
|
├── postcss.config.js # PostCSS configuration
|
||||||
|
├── eslint.config.js # ESLint configuration
|
||||||
|
├── LICENSE # Project license
|
||||||
|
└── README.md # This file
|
||||||
|
```
|
||||||
|
|
||||||
|
## Database Schema
|
||||||
|
|
||||||
|
The application uses Supabase with the following main tables:
|
||||||
|
|
||||||
|
- **profiles**: User profiles with username and theme preferences
|
||||||
|
- **decks**: User decks with name, format, and timestamps
|
||||||
|
- **deck_cards**: Cards in decks with quantity and commander status
|
||||||
|
- **collections**: User card collections with quantities
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Node.js (v18 or higher)
|
||||||
|
- npm or pnpm
|
||||||
|
- Supabase account and project
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
1. Clone the repository:
|
||||||
|
```bash
|
||||||
|
git clone <repository-url>
|
||||||
|
cd deckerr
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Install dependencies:
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
# or
|
||||||
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Set up environment variables:
|
||||||
|
Create a `.env` file with your Supabase credentials:
|
||||||
|
```
|
||||||
|
VITE_SUPABASE_URL=your_supabase_url
|
||||||
|
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Run the development server:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Open your browser to `http://localhost:5173`
|
||||||
|
|
||||||
|
## Available Scripts
|
||||||
|
|
||||||
|
- `npm run dev` - Start development server
|
||||||
|
- `npm run build` - Build for production
|
||||||
|
- `npm run preview` - Preview production build
|
||||||
|
- `npm run lint` - Run ESLint
|
||||||
|
|
||||||
|
## Features in Detail
|
||||||
|
|
||||||
|
### Deck Builder
|
||||||
|
Build and customize your Magic decks with support for different formats. The deck editor validates your deck composition according to format rules.
|
||||||
|
|
||||||
|
### Collection Manager
|
||||||
|
Track which cards you own and their quantities, making it easy to see what cards you have available when building decks.
|
||||||
|
|
||||||
|
### Card Search
|
||||||
|
Search through Magic cards using various filters and criteria to find exactly what you need for your deck.
|
||||||
|
|
||||||
|
### Life Counter
|
||||||
|
A built-in life counter for tracking player life totals during games, with an animated interface.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
See the LICENSE file for details.
|
||||||
1
dev-dist/registerSW.js
Normal file
1
dev-dist/registerSW.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
if('serviceWorker' in navigator) navigator.serviceWorker.register('/dev-sw.js?dev-sw', { scope: '/', type: 'classic' })
|
||||||
110
dev-dist/sw.js
Normal file
110
dev-dist/sw.js
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
/**
|
||||||
|
* Copyright 2018 Google Inc. All Rights Reserved.
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// If the loader is already loaded, just stop.
|
||||||
|
if (!self.define) {
|
||||||
|
let registry = {};
|
||||||
|
|
||||||
|
// Used for `eval` and `importScripts` where we can't get script URL by other means.
|
||||||
|
// In both cases, it's safe to use a global var because those functions are synchronous.
|
||||||
|
let nextDefineUri;
|
||||||
|
|
||||||
|
const singleRequire = (uri, parentUri) => {
|
||||||
|
uri = new URL(uri + ".js", parentUri).href;
|
||||||
|
return registry[uri] || (
|
||||||
|
|
||||||
|
new Promise(resolve => {
|
||||||
|
if ("document" in self) {
|
||||||
|
const script = document.createElement("script");
|
||||||
|
script.src = uri;
|
||||||
|
script.onload = resolve;
|
||||||
|
document.head.appendChild(script);
|
||||||
|
} else {
|
||||||
|
nextDefineUri = uri;
|
||||||
|
importScripts(uri);
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
.then(() => {
|
||||||
|
let promise = registry[uri];
|
||||||
|
if (!promise) {
|
||||||
|
throw new Error(`Module ${uri} didn’t register its module`);
|
||||||
|
}
|
||||||
|
return promise;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
self.define = (depsNames, factory) => {
|
||||||
|
const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href;
|
||||||
|
if (registry[uri]) {
|
||||||
|
// Module is already loading or loaded.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let exports = {};
|
||||||
|
const require = depUri => singleRequire(depUri, uri);
|
||||||
|
const specialDeps = {
|
||||||
|
module: { uri },
|
||||||
|
exports,
|
||||||
|
require
|
||||||
|
};
|
||||||
|
registry[uri] = Promise.all(depsNames.map(
|
||||||
|
depName => specialDeps[depName] || require(depName)
|
||||||
|
)).then(deps => {
|
||||||
|
factory(...deps);
|
||||||
|
return exports;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
define(['./workbox-ca84f546'], (function (workbox) { 'use strict';
|
||||||
|
|
||||||
|
self.skipWaiting();
|
||||||
|
workbox.clientsClaim();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The precacheAndRoute() method efficiently caches and responds to
|
||||||
|
* requests for URLs in the manifest.
|
||||||
|
* See https://goo.gl/S9QRab
|
||||||
|
*/
|
||||||
|
workbox.precacheAndRoute([{
|
||||||
|
"url": "registerSW.js",
|
||||||
|
"revision": "3ca0b8505b4bec776b69afdba2768812"
|
||||||
|
}, {
|
||||||
|
"url": "index.html",
|
||||||
|
"revision": "0.obrcsn1e2cs"
|
||||||
|
}], {});
|
||||||
|
workbox.cleanupOutdatedCaches();
|
||||||
|
workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), {
|
||||||
|
allowlist: [/^\/$/]
|
||||||
|
}));
|
||||||
|
workbox.registerRoute(/^https:\/\/api\.scryfall\.com\/.*/i, new workbox.CacheFirst({
|
||||||
|
"cacheName": "scryfall-cache",
|
||||||
|
plugins: [new workbox.ExpirationPlugin({
|
||||||
|
maxEntries: 500,
|
||||||
|
maxAgeSeconds: 604800
|
||||||
|
}), new workbox.CacheableResponsePlugin({
|
||||||
|
statuses: [0, 200]
|
||||||
|
})]
|
||||||
|
}), 'GET');
|
||||||
|
workbox.registerRoute(/^https:\/\/cards\.scryfall\.io\/.*/i, new workbox.CacheFirst({
|
||||||
|
"cacheName": "card-images-cache",
|
||||||
|
plugins: [new workbox.ExpirationPlugin({
|
||||||
|
maxEntries: 1000,
|
||||||
|
maxAgeSeconds: 2592000
|
||||||
|
}), new workbox.CacheableResponsePlugin({
|
||||||
|
statuses: [0, 200]
|
||||||
|
})]
|
||||||
|
}), 'GET');
|
||||||
|
|
||||||
|
}));
|
||||||
4556
dev-dist/workbox-ca84f546.js
Normal file
4556
dev-dist/workbox-ca84f546.js
Normal file
File diff suppressed because it is too large
Load Diff
201
docker-compose.selfhosted.yml
Normal file
201
docker-compose.selfhosted.yml
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
# Full self-hosted deployment with Supabase included
|
||||||
|
# This includes PostgreSQL, Auth, REST API, and the Deckerr frontend
|
||||||
|
|
||||||
|
services:
|
||||||
|
# ============================================
|
||||||
|
# DECKERR FRONTEND
|
||||||
|
# ============================================
|
||||||
|
deckerr:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
- VITE_SUPABASE_URL=http://${SITE_URL:-localhost}:${KONG_HTTP_PORT:-8000}
|
||||||
|
- VITE_SUPABASE_ANON_KEY=${ANON_KEY}
|
||||||
|
container_name: deckerr
|
||||||
|
ports:
|
||||||
|
- "${DECKERR_PORT:-3000}:80"
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
kong:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# SUPABASE SERVICES
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# PostgreSQL Database
|
||||||
|
db:
|
||||||
|
image: supabase/postgres:15.1.1.78
|
||||||
|
container_name: supabase-db
|
||||||
|
healthcheck:
|
||||||
|
test: pg_isready -U postgres -h localhost
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
ports:
|
||||||
|
- "${POSTGRES_PORT:-5432}:5432"
|
||||||
|
environment:
|
||||||
|
POSTGRES_HOST: /var/run/postgresql
|
||||||
|
PGPORT: 5432
|
||||||
|
POSTGRES_PORT: 5432
|
||||||
|
PGPASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
PGDATABASE: postgres
|
||||||
|
POSTGRES_DB: postgres
|
||||||
|
volumes:
|
||||||
|
- supabase-db-data:/var/lib/postgresql/data
|
||||||
|
- ./supabase/migrations:/docker-entrypoint-initdb.d/migrations
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# Supabase Kong API Gateway
|
||||||
|
kong:
|
||||||
|
image: kong:2.8.1
|
||||||
|
container_name: supabase-kong
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "${KONG_HTTP_PORT:-8000}:8000/tcp"
|
||||||
|
- "${KONG_HTTPS_PORT:-8443}:8443/tcp"
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
KONG_DATABASE: "off"
|
||||||
|
KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
|
||||||
|
KONG_DNS_ORDER: LAST,A,CNAME
|
||||||
|
KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth
|
||||||
|
KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k
|
||||||
|
KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k
|
||||||
|
SUPABASE_ANON_KEY: ${ANON_KEY}
|
||||||
|
SUPABASE_SERVICE_KEY: ${SERVICE_ROLE_KEY}
|
||||||
|
volumes:
|
||||||
|
- ./docker/kong.yml:/home/kong/kong.yml:ro
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "kong", "health"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
# Supabase Auth (GoTrue)
|
||||||
|
auth:
|
||||||
|
image: supabase/gotrue:v2.143.0
|
||||||
|
container_name: supabase-auth
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9999/health"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
GOTRUE_API_HOST: 0.0.0.0
|
||||||
|
GOTRUE_API_PORT: 9999
|
||||||
|
API_EXTERNAL_URL: ${API_EXTERNAL_URL:-http://localhost:8000}
|
||||||
|
|
||||||
|
GOTRUE_DB_DRIVER: postgres
|
||||||
|
GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:${POSTGRES_PASSWORD}@db:5432/postgres
|
||||||
|
|
||||||
|
GOTRUE_SITE_URL: ${SITE_URL:-http://localhost:3000}
|
||||||
|
GOTRUE_URI_ALLOW_LIST: ${ADDITIONAL_REDIRECT_URLS:-}
|
||||||
|
GOTRUE_DISABLE_SIGNUP: ${DISABLE_SIGNUP:-false}
|
||||||
|
|
||||||
|
GOTRUE_JWT_ADMIN_ROLES: service_role
|
||||||
|
GOTRUE_JWT_AUD: authenticated
|
||||||
|
GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
|
||||||
|
GOTRUE_JWT_EXP: ${JWT_EXPIRY:-3600}
|
||||||
|
GOTRUE_JWT_SECRET: ${JWT_SECRET}
|
||||||
|
|
||||||
|
GOTRUE_EXTERNAL_EMAIL_ENABLED: ${ENABLE_EMAIL_SIGNUP:-true}
|
||||||
|
GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: ${ENABLE_ANONYMOUS_USERS:-false}
|
||||||
|
GOTRUE_MAILER_AUTOCONFIRM: ${ENABLE_EMAIL_AUTOCONFIRM:-false}
|
||||||
|
|
||||||
|
GOTRUE_SMTP_HOST: ${SMTP_HOST:-}
|
||||||
|
GOTRUE_SMTP_PORT: ${SMTP_PORT:-587}
|
||||||
|
GOTRUE_SMTP_USER: ${SMTP_USER:-}
|
||||||
|
GOTRUE_SMTP_PASS: ${SMTP_PASS:-}
|
||||||
|
GOTRUE_SMTP_ADMIN_EMAIL: ${SMTP_ADMIN_EMAIL:-}
|
||||||
|
GOTRUE_SMTP_SENDER_NAME: ${SMTP_SENDER_NAME:-Deckerr}
|
||||||
|
GOTRUE_MAILER_URLPATHS_INVITE: /auth/v1/verify
|
||||||
|
GOTRUE_MAILER_URLPATHS_CONFIRMATION: /auth/v1/verify
|
||||||
|
GOTRUE_MAILER_URLPATHS_RECOVERY: /auth/v1/verify
|
||||||
|
GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: /auth/v1/verify
|
||||||
|
|
||||||
|
# Supabase REST API (PostgREST)
|
||||||
|
rest:
|
||||||
|
image: postgrest/postgrest:v12.0.1
|
||||||
|
container_name: supabase-rest
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
PGRST_DB_URI: postgres://authenticator:${POSTGRES_PASSWORD}@db:5432/postgres
|
||||||
|
PGRST_DB_SCHEMAS: ${PGRST_DB_SCHEMAS:-public,graphql_public}
|
||||||
|
PGRST_DB_ANON_ROLE: anon
|
||||||
|
PGRST_JWT_SECRET: ${JWT_SECRET}
|
||||||
|
PGRST_DB_USE_LEGACY_GUCS: "false"
|
||||||
|
PGRST_APP_SETTINGS_JWT_SECRET: ${JWT_SECRET}
|
||||||
|
PGRST_APP_SETTINGS_JWT_EXP: ${JWT_EXPIRY:-3600}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -f http://localhost:3000/ready || exit 1"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
|
||||||
|
# Supabase Realtime
|
||||||
|
realtime:
|
||||||
|
image: supabase/realtime:v2.28.32
|
||||||
|
container_name: supabase-realtime
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-sSfL", "--head", "-o", "/dev/null", "-H", "Authorization: Bearer ${ANON_KEY}", "http://localhost:4000/api/tenants/realtime-dev/health"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
PORT: 4000
|
||||||
|
DB_HOST: db
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_USER: supabase_admin
|
||||||
|
DB_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
DB_NAME: postgres
|
||||||
|
DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'
|
||||||
|
DB_ENC_KEY: supabaserealtime
|
||||||
|
API_JWT_SECRET: ${JWT_SECRET}
|
||||||
|
SECRET_KEY_BASE: ${SECRET_KEY_BASE:-UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq}
|
||||||
|
ERL_AFLAGS: -proto_dist inet_tcp
|
||||||
|
DNS_NODES: "''"
|
||||||
|
RLIMIT_NOFILE: "10000"
|
||||||
|
APP_NAME: realtime
|
||||||
|
SEED_SELF_HOST: true
|
||||||
|
REPLICATION_MODE: RLS
|
||||||
|
REPLICATION_POLL_INTERVAL: 100
|
||||||
|
SECURE_CHANNELS: "true"
|
||||||
|
SLOT_NAME: supabase_realtime_rls
|
||||||
|
TEMPORARY_SLOT: "true"
|
||||||
|
|
||||||
|
# Supabase Meta (for Studio - optional)
|
||||||
|
meta:
|
||||||
|
image: supabase/postgres-meta:v0.80.0
|
||||||
|
container_name: supabase-meta
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
PG_META_PORT: 8080
|
||||||
|
PG_META_DB_HOST: db
|
||||||
|
PG_META_DB_PORT: 5432
|
||||||
|
PG_META_DB_NAME: postgres
|
||||||
|
PG_META_DB_USER: supabase_admin
|
||||||
|
PG_META_DB_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
supabase-db-data:
|
||||||
22
docker-compose.yml
Normal file
22
docker-compose.yml
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
# Simple deployment - Uses external Supabase (hosted or self-hosted separately)
|
||||||
|
# For full self-hosted setup with Supabase included, use docker-compose.selfhosted.yml
|
||||||
|
|
||||||
|
services:
|
||||||
|
deckerr:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
|
||||||
|
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
|
||||||
|
container_name: deckerr
|
||||||
|
ports:
|
||||||
|
- "${PORT:-3000}:80"
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:80"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
138
docker/kong.yml
Normal file
138
docker/kong.yml
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
_format_version: "2.1"
|
||||||
|
_transform: true
|
||||||
|
|
||||||
|
###
|
||||||
|
### Consumers / Users
|
||||||
|
###
|
||||||
|
consumers:
|
||||||
|
- username: DASHBOARD
|
||||||
|
- username: anon
|
||||||
|
keyauth_credentials:
|
||||||
|
- key: ${SUPABASE_ANON_KEY}
|
||||||
|
- username: service_role
|
||||||
|
keyauth_credentials:
|
||||||
|
- key: ${SUPABASE_SERVICE_KEY}
|
||||||
|
|
||||||
|
###
|
||||||
|
### Access Control Lists
|
||||||
|
###
|
||||||
|
acls:
|
||||||
|
- consumer: anon
|
||||||
|
group: anon
|
||||||
|
- consumer: service_role
|
||||||
|
group: admin
|
||||||
|
|
||||||
|
###
|
||||||
|
### API Routes
|
||||||
|
###
|
||||||
|
services:
|
||||||
|
## Open Auth routes
|
||||||
|
- name: auth-v1-open
|
||||||
|
url: http://auth:9999/verify
|
||||||
|
routes:
|
||||||
|
- name: auth-v1-open
|
||||||
|
strip_path: true
|
||||||
|
paths:
|
||||||
|
- /auth/v1/verify
|
||||||
|
plugins:
|
||||||
|
- name: cors
|
||||||
|
- name: auth-v1-open-callback
|
||||||
|
url: http://auth:9999/callback
|
||||||
|
routes:
|
||||||
|
- name: auth-v1-open-callback
|
||||||
|
strip_path: true
|
||||||
|
paths:
|
||||||
|
- /auth/v1/callback
|
||||||
|
plugins:
|
||||||
|
- name: cors
|
||||||
|
- name: auth-v1-open-authorize
|
||||||
|
url: http://auth:9999/authorize
|
||||||
|
routes:
|
||||||
|
- name: auth-v1-open-authorize
|
||||||
|
strip_path: true
|
||||||
|
paths:
|
||||||
|
- /auth/v1/authorize
|
||||||
|
plugins:
|
||||||
|
- name: cors
|
||||||
|
|
||||||
|
## Secure Auth routes
|
||||||
|
- name: auth-v1
|
||||||
|
_comment: "GoTrue: /auth/v1/* -> http://auth:9999/*"
|
||||||
|
url: http://auth:9999/
|
||||||
|
routes:
|
||||||
|
- name: auth-v1-all
|
||||||
|
strip_path: true
|
||||||
|
paths:
|
||||||
|
- /auth/v1/
|
||||||
|
plugins:
|
||||||
|
- name: cors
|
||||||
|
- name: key-auth
|
||||||
|
config:
|
||||||
|
hide_credentials: false
|
||||||
|
- name: acl
|
||||||
|
config:
|
||||||
|
hide_groups_header: true
|
||||||
|
allow:
|
||||||
|
- admin
|
||||||
|
- anon
|
||||||
|
|
||||||
|
## Secure REST routes
|
||||||
|
- name: rest-v1
|
||||||
|
_comment: "PostgREST: /rest/v1/* -> http://rest:3000/*"
|
||||||
|
url: http://rest:3000/
|
||||||
|
routes:
|
||||||
|
- name: rest-v1-all
|
||||||
|
strip_path: true
|
||||||
|
paths:
|
||||||
|
- /rest/v1/
|
||||||
|
plugins:
|
||||||
|
- name: cors
|
||||||
|
- name: key-auth
|
||||||
|
config:
|
||||||
|
hide_credentials: false
|
||||||
|
- name: acl
|
||||||
|
config:
|
||||||
|
hide_groups_header: true
|
||||||
|
allow:
|
||||||
|
- admin
|
||||||
|
- anon
|
||||||
|
|
||||||
|
## Realtime routes
|
||||||
|
- name: realtime-v1
|
||||||
|
_comment: "Realtime: /realtime/v1/* -> ws://realtime:4000/socket/*"
|
||||||
|
url: http://realtime:4000/socket/
|
||||||
|
routes:
|
||||||
|
- name: realtime-v1-all
|
||||||
|
strip_path: true
|
||||||
|
paths:
|
||||||
|
- /realtime/v1/
|
||||||
|
plugins:
|
||||||
|
- name: cors
|
||||||
|
- name: key-auth
|
||||||
|
config:
|
||||||
|
hide_credentials: false
|
||||||
|
- name: acl
|
||||||
|
config:
|
||||||
|
hide_groups_header: true
|
||||||
|
allow:
|
||||||
|
- admin
|
||||||
|
- anon
|
||||||
|
|
||||||
|
## Meta routes (for Supabase Studio)
|
||||||
|
- name: meta
|
||||||
|
_comment: "pg-meta: /pg/* -> http://meta:8080/*"
|
||||||
|
url: http://meta:8080/
|
||||||
|
routes:
|
||||||
|
- name: meta-all
|
||||||
|
strip_path: true
|
||||||
|
paths:
|
||||||
|
- /pg/
|
||||||
|
plugins:
|
||||||
|
- name: key-auth
|
||||||
|
config:
|
||||||
|
hide_credentials: false
|
||||||
|
- name: acl
|
||||||
|
config:
|
||||||
|
hide_groups_header: true
|
||||||
|
allow:
|
||||||
|
- admin
|
||||||
27
index.html
27
index.html
@@ -2,12 +2,31 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
<title>Vite + React + TS</title>
|
|
||||||
|
<!-- Primary Meta Tags -->
|
||||||
|
<title>Deckerr - Card Deck Manager</title>
|
||||||
|
<meta name="title" content="Deckerr - Card Deck Manager" />
|
||||||
|
<meta name="description" content="Manage your trading card game decks on the go. Build, organize, and track your card collection." />
|
||||||
|
|
||||||
|
<!-- PWA Meta Tags -->
|
||||||
|
<meta name="theme-color" content="#0f172a" />
|
||||||
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||||
|
<meta name="apple-mobile-web-app-title" content="Deckerr" />
|
||||||
|
|
||||||
|
<!-- Apple Touch Icons -->
|
||||||
|
<link rel="apple-touch-icon" href="/icon.svg" />
|
||||||
|
<link rel="apple-touch-icon" sizes="180x180" href="/icon.svg" />
|
||||||
|
|
||||||
|
<!-- MS Application -->
|
||||||
|
<meta name="msapplication-TileColor" content="#0f172a" />
|
||||||
|
<meta name="msapplication-config" content="/browserconfig.xml" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
29
nginx.conf
Normal file
29
nginx.conf
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# Gzip compression
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_proxied expired no-cache no-store private auth;
|
||||||
|
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/javascript application/json;
|
||||||
|
|
||||||
|
# Cache static assets
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Handle SPA routing - serve index.html for all routes
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Security headers
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
}
|
||||||
12641
package-lock.json
generated
12641
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "vite-react-typescript-starter",
|
"name": "deckerr",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "1.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -29,6 +29,7 @@
|
|||||||
"tailwindcss": "^3.4.1",
|
"tailwindcss": "^3.4.1",
|
||||||
"typescript": "^5.5.3",
|
"typescript": "^5.5.3",
|
||||||
"typescript-eslint": "^8.3.0",
|
"typescript-eslint": "^8.3.0",
|
||||||
"vite": "^5.4.2"
|
"vite": "^5.4.2",
|
||||||
|
"vite-plugin-pwa": "^1.1.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
9
public/browserconfig.xml
Normal file
9
public/browserconfig.xml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<browserconfig>
|
||||||
|
<msapplication>
|
||||||
|
<tile>
|
||||||
|
<square150x150logo src="/icon.svg"/>
|
||||||
|
<TileColor>#0f172a</TileColor>
|
||||||
|
</tile>
|
||||||
|
</msapplication>
|
||||||
|
</browserconfig>
|
||||||
23
public/icon.svg
Normal file
23
public/icon.svg
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<!-- Background -->
|
||||||
|
<rect width="512" height="512" fill="#0f172a" rx="128"/>
|
||||||
|
|
||||||
|
<!-- Card stack effect - back card -->
|
||||||
|
<rect x="120" y="130" width="240" height="320" rx="16" fill="#1e293b" transform="rotate(-8 240 290)"/>
|
||||||
|
|
||||||
|
<!-- Card stack effect - middle card -->
|
||||||
|
<rect x="120" y="130" width="240" height="320" rx="16" fill="#334155" transform="rotate(-4 240 290)"/>
|
||||||
|
|
||||||
|
<!-- Front card -->
|
||||||
|
<rect x="120" y="130" width="240" height="320" rx="16" fill="#475569"/>
|
||||||
|
<rect x="135" y="145" width="210" height="290" rx="12" fill="#1e293b"/>
|
||||||
|
|
||||||
|
<!-- Card details/design -->
|
||||||
|
<circle cx="240" cy="200" r="40" fill="#3b82f6" opacity="0.6"/>
|
||||||
|
<rect x="160" y="280" width="160" height="12" rx="6" fill="#3b82f6" opacity="0.8"/>
|
||||||
|
<rect x="160" y="310" width="120" height="12" rx="6" fill="#3b82f6" opacity="0.6"/>
|
||||||
|
<rect x="160" y="340" width="140" height="12" rx="6" fill="#3b82f6" opacity="0.4"/>
|
||||||
|
|
||||||
|
<!-- "D" Letter overlay -->
|
||||||
|
<text x="256" y="310" font-family="Arial, sans-serif" font-size="160" font-weight="bold" fill="#3b82f6" text-anchor="middle" opacity="0.15">D</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
BIN
public/mana-color/forest.png
Normal file
BIN
public/mana-color/forest.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 139 KiB |
BIN
public/mana-color/island.png
Normal file
BIN
public/mana-color/island.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
BIN
public/mana-color/moutain.png
Normal file
BIN
public/mana-color/moutain.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 163 KiB |
BIN
public/mana-color/plains.png
Normal file
BIN
public/mana-color/plains.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 179 KiB |
BIN
public/mana-color/swamp.png
Normal file
BIN
public/mana-color/swamp.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 153 KiB |
111
public/manifest.json
Normal file
111
public/manifest.json
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
{
|
||||||
|
"name": "Deckerr - Card Deck Manager",
|
||||||
|
"short_name": "Deckerr",
|
||||||
|
"description": "Manage your trading card game decks on the go",
|
||||||
|
"theme_color": "#0f172a",
|
||||||
|
"background_color": "#0f172a",
|
||||||
|
"display": "standalone",
|
||||||
|
"orientation": "portrait",
|
||||||
|
"scope": "/",
|
||||||
|
"start_url": "/",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "/icon-72x72.png",
|
||||||
|
"sizes": "72x72",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-96x96.png",
|
||||||
|
"sizes": "96x96",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-128x128.png",
|
||||||
|
"sizes": "128x128",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-144x144.png",
|
||||||
|
"sizes": "144x144",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-152x152.png",
|
||||||
|
"sizes": "152x152",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-192x192.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-384x384.png",
|
||||||
|
"sizes": "384x384",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-512x512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-maskable-192x192.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-maskable-512x512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"screenshots": [
|
||||||
|
{
|
||||||
|
"src": "/screenshot-mobile-1.png",
|
||||||
|
"sizes": "540x720",
|
||||||
|
"type": "image/png",
|
||||||
|
"form_factor": "narrow"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/screenshot-desktop-1.png",
|
||||||
|
"sizes": "1280x720",
|
||||||
|
"type": "image/png",
|
||||||
|
"form_factor": "wide"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"categories": ["games", "utilities"],
|
||||||
|
"shortcuts": [
|
||||||
|
{
|
||||||
|
"name": "My Decks",
|
||||||
|
"short_name": "Decks",
|
||||||
|
"description": "View your deck collection",
|
||||||
|
"url": "/?page=home",
|
||||||
|
"icons": [{ "src": "/icon-192x192.png", "sizes": "192x192" }]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Search Cards",
|
||||||
|
"short_name": "Search",
|
||||||
|
"description": "Search for cards",
|
||||||
|
"url": "/?page=search",
|
||||||
|
"icons": [{ "src": "/icon-192x192.png", "sizes": "192x192" }]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Life Counter",
|
||||||
|
"short_name": "Life",
|
||||||
|
"description": "Track life totals",
|
||||||
|
"url": "/?page=life-counter",
|
||||||
|
"icons": [{ "src": "/icon-192x192.png", "sizes": "192x192" }]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
24
src/App.tsx
24
src/App.tsx
@@ -8,9 +8,13 @@ import React, { useState } from 'react';
|
|||||||
import Profile from './components/Profile';
|
import Profile from './components/Profile';
|
||||||
import CardSearch from './components/CardSearch';
|
import CardSearch from './components/CardSearch';
|
||||||
import LifeCounter from './components/LifeCounter';
|
import LifeCounter from './components/LifeCounter';
|
||||||
|
import Friends from './components/Friends';
|
||||||
|
import Trades from './components/Trades';
|
||||||
|
import Community from './components/Community';
|
||||||
|
import PWAInstallPrompt from './components/PWAInstallPrompt';
|
||||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||||
|
|
||||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'profile' | 'search' | 'life-counter';
|
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'profile' | 'search' | 'life-counter' | 'friends' | 'trades' | 'community';
|
||||||
|
|
||||||
function AppContent() {
|
function AppContent() {
|
||||||
const [currentPage, setCurrentPage] = useState<Page>('home');
|
const [currentPage, setCurrentPage] = useState<Page>('home');
|
||||||
@@ -38,10 +42,13 @@ import React, { useState } from 'react';
|
|||||||
switch (currentPage) {
|
switch (currentPage) {
|
||||||
case 'home':
|
case 'home':
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 text-white p-6 animate-fade-in">
|
<div className="bg-gray-900 text-white p-3 sm:p-6 animate-fade-in">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<h1 className="text-3xl font-bold mb-6 animate-slide-in-left">My Decks</h1>
|
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6 animate-slide-in-left">My Decks</h1>
|
||||||
<DeckList onDeckEdit={handleDeckEdit} />
|
<DeckList
|
||||||
|
onDeckEdit={handleDeckEdit}
|
||||||
|
onCreateDeck={() => setCurrentPage('deck')}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -65,6 +72,12 @@ import React, { useState } from 'react';
|
|||||||
return <CardSearch />;
|
return <CardSearch />;
|
||||||
case 'life-counter':
|
case 'life-counter':
|
||||||
return <LifeCounter />;
|
return <LifeCounter />;
|
||||||
|
case 'friends':
|
||||||
|
return <Friends />;
|
||||||
|
case 'trades':
|
||||||
|
return <Trades />;
|
||||||
|
case 'community':
|
||||||
|
return <Community />;
|
||||||
case 'login':
|
case 'login':
|
||||||
return <LoginForm />;
|
return <LoginForm />;
|
||||||
default:
|
default:
|
||||||
@@ -75,7 +88,8 @@ import React, { useState } from 'react';
|
|||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900">
|
<div className="min-h-screen bg-gray-900">
|
||||||
<Navigation currentPage={currentPage} setCurrentPage={setCurrentPage} />
|
<Navigation currentPage={currentPage} setCurrentPage={setCurrentPage} />
|
||||||
{renderPage()}
|
{renderPage()}
|
||||||
|
<PWAInstallPrompt />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { searchCards } from '../services/api';
|
import { RefreshCw, PackagePlus, Loader2, CheckCircle, XCircle, Trash2 } from 'lucide-react';
|
||||||
|
import { searchCards, getUserCollection, addCardToCollection } from '../services/api';
|
||||||
import { Card } from '../types';
|
import { Card } from '../types';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import MagicCard from './MagicCard';
|
import MagicCard from './MagicCard';
|
||||||
|
import { getManaIconPath } from './ManaCost';
|
||||||
|
|
||||||
const CardSearch = () => {
|
const CardSearch = () => {
|
||||||
|
const { user } = useAuth();
|
||||||
const [cardName, setCardName] = useState('');
|
const [cardName, setCardName] = useState('');
|
||||||
const [text, setText] = useState('');
|
const [text, setText] = useState('');
|
||||||
const [rulesText, setRulesText] = useState('');
|
const [rulesText, setRulesText] = useState('');
|
||||||
@@ -40,6 +44,85 @@ const CardSearch = () => {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Collection state
|
||||||
|
const [userCollection, setUserCollection] = useState<Map<string, number>>(new Map());
|
||||||
|
const [addingCardId, setAddingCardId] = useState<string | null>(null);
|
||||||
|
const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map());
|
||||||
|
const [snackbar, setSnackbar] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
|
||||||
|
|
||||||
|
// Load user collection
|
||||||
|
useEffect(() => {
|
||||||
|
const loadUserCollection = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
try {
|
||||||
|
const collection = await getUserCollection(user.id);
|
||||||
|
setUserCollection(collection);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading user collection:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
loadUserCollection();
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
// Helper function to check if a card has an actual back face
|
||||||
|
const isDoubleFaced = (card: Card) => {
|
||||||
|
const backFaceLayouts = ['transform', 'modal_dfc', 'double_faced_token', 'reversible_card'];
|
||||||
|
return card.card_faces && card.card_faces.length > 1 && backFaceLayouts.includes(card.layout);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get current face index for a card
|
||||||
|
const getCurrentFaceIndex = (cardId: string) => {
|
||||||
|
return cardFaceIndex.get(cardId) || 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Toggle card face
|
||||||
|
const toggleCardFace = (cardId: string, totalFaces: number) => {
|
||||||
|
setCardFaceIndex(prev => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const currentIndex = prev.get(cardId) || 0;
|
||||||
|
const nextIndex = (currentIndex + 1) % totalFaces;
|
||||||
|
newMap.set(cardId, nextIndex);
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get card image for current face
|
||||||
|
const getCardImageUri = (card: Card, faceIndex: number = 0) => {
|
||||||
|
if (isDoubleFaced(card) && card.card_faces) {
|
||||||
|
return card.card_faces[faceIndex]?.image_uris?.normal || card.card_faces[faceIndex]?.image_uris?.small;
|
||||||
|
}
|
||||||
|
return card.image_uris?.normal || card.image_uris?.small || card.card_faces?.[0]?.image_uris?.normal;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add card to collection
|
||||||
|
const handleAddCardToCollection = async (cardId: string) => {
|
||||||
|
if (!user) {
|
||||||
|
setSnackbar({ message: 'Please log in to add cards to your collection', type: 'error' });
|
||||||
|
setTimeout(() => setSnackbar(null), 3000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setAddingCardId(cardId);
|
||||||
|
await addCardToCollection(user.id, cardId, 1);
|
||||||
|
|
||||||
|
setUserCollection(prev => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const currentQty = newMap.get(cardId) || 0;
|
||||||
|
newMap.set(cardId, currentQty + 1);
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
|
||||||
|
setSnackbar({ message: 'Card added to collection!', type: 'success' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error adding card to collection:', error);
|
||||||
|
setSnackbar({ message: 'Failed to add card to collection', type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setAddingCardId(null);
|
||||||
|
setTimeout(() => setSnackbar(null), 3000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleSearch = async (e: React.FormEvent) => {
|
const handleSearch = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -110,9 +193,9 @@ const CardSearch = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 text-white p-6">
|
<div className="bg-gray-900 text-white p-3 sm:p-6">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<h1 className="text-3xl font-bold mb-6">Card Search</h1>
|
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Card Search</h1>
|
||||||
<form onSubmit={handleSearch} className="mb-8 space-y-4">
|
<form onSubmit={handleSearch} className="mb-8 space-y-4">
|
||||||
{/* Card Details */}
|
{/* Card Details */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
@@ -137,7 +220,7 @@ const CardSearch = () => {
|
|||||||
className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-white"
|
className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-white"
|
||||||
placeholder="Rules Text (~ for card name)"
|
placeholder="Rules Text (~ for card name)"
|
||||||
/>
|
/>
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={typeLine}
|
value={typeLine}
|
||||||
@@ -177,9 +260,11 @@ const CardSearch = () => {
|
|||||||
onChange={() => setColors({ ...colors, [color]: !active })}
|
onChange={() => setColors({ ...colors, [color]: !active })}
|
||||||
className="rounded border-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
className="rounded border-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
/>
|
/>
|
||||||
<span style={{ fontSize: '1.5em' }}>
|
{getManaIconPath(color) ? (
|
||||||
{color === 'W' ? '⚪' : color === 'U' ? '🔵' : color === 'B' ? '⚫' : color === 'R' ? '🔴' : color === 'G' ? '🟢' : '🟤'}
|
<img src={getManaIconPath(color)!} alt={color} className="w-6 h-6" />
|
||||||
</span>
|
) : (
|
||||||
|
<span className="w-6 h-6 flex items-center justify-center bg-gray-500 text-white font-bold rounded-full text-sm">{color}</span>
|
||||||
|
)}
|
||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -203,9 +288,11 @@ const CardSearch = () => {
|
|||||||
onChange={() => setCommanderColors({ ...commanderColors, [color]: !active })}
|
onChange={() => setCommanderColors({ ...commanderColors, [color]: !active })}
|
||||||
className="rounded border-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
className="rounded border-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
/>
|
/>
|
||||||
<span style={{ fontSize: '1.5em' }}>
|
{getManaIconPath(color) ? (
|
||||||
{color === 'W' ? '⚪' : color === 'U' ? '🔵' : color === 'B' ? '⚫' : color === 'R' ? '🔴' : color === 'G' ? '🟢' : '🟤'}
|
<img src={getManaIconPath(color)!} alt={color} className="w-6 h-6" />
|
||||||
</span>
|
) : (
|
||||||
|
<span className="w-6 h-6 flex items-center justify-center bg-gray-500 text-white font-bold rounded-full text-sm">{color}</span>
|
||||||
|
)}
|
||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -213,25 +300,32 @@ const CardSearch = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mana Cost */}
|
{/* Mana Cost */}
|
||||||
<div className="grid grid-cols-3 md:grid-cols-6 gap-2">
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-2">
|
||||||
{Object.entries(manaCost).map(([color, count]) => (
|
{Object.entries(manaCost).map(([color, count]) => {
|
||||||
<div key={color} className="flex items-center space-x-2">
|
const iconPath = getManaIconPath(color);
|
||||||
<span style={{ fontSize: '1.5em' }}>
|
return (
|
||||||
{color === 'W' ? '⚪' : color === 'U' ? '🔵' : color === 'B' ? '⚫' : color === 'R' ? '🔴' : color === 'G' ? '🟢' : '🟤'}
|
<div key={color} className="flex items-center space-x-2">
|
||||||
</span>
|
{iconPath ? (
|
||||||
<input
|
<img src={iconPath} alt={color} className="w-6 h-6 md:w-8 md:h-8" />
|
||||||
type="number"
|
) : (
|
||||||
value={count}
|
<span className="w-6 h-6 md:w-8 md:h-8 flex items-center justify-center bg-gray-500 text-white font-bold rounded-full text-sm">
|
||||||
onChange={(e) => setManaCost({ ...manaCost, [color]: parseInt(e.target.value) })}
|
{color}
|
||||||
className="w-16 px-2 py-1 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-white"
|
</span>
|
||||||
min="0"
|
)}
|
||||||
/>
|
<input
|
||||||
</div>
|
type="number"
|
||||||
))}
|
value={count}
|
||||||
|
onChange={(e) => setManaCost({ ...manaCost, [color]: parseInt(e.target.value) })}
|
||||||
|
className="w-14 sm:w-16 px-2 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-white"
|
||||||
|
min="0"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Stats */}
|
{/* Stats */}
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
<select
|
<select
|
||||||
value={manaValueComparison}
|
value={manaValueComparison}
|
||||||
onChange={(e) => setManaValueComparison(e.target.value)}
|
onChange={(e) => setManaValueComparison(e.target.value)}
|
||||||
@@ -272,7 +366,7 @@ const CardSearch = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Formats */}
|
{/* Formats */}
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
<select
|
<select
|
||||||
value={format}
|
value={format}
|
||||||
onChange={(e) => setFormat(e.target.value)}
|
onChange={(e) => setFormat(e.target.value)}
|
||||||
@@ -314,7 +408,7 @@ const CardSearch = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Sets */}
|
{/* Sets */}
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={set}
|
value={set}
|
||||||
@@ -350,7 +444,7 @@ const CardSearch = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Criteria */}
|
{/* Criteria */}
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={criteria}
|
value={criteria}
|
||||||
@@ -377,7 +471,7 @@ const CardSearch = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Prices */}
|
{/* Prices */}
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
<select
|
<select
|
||||||
value={currency}
|
value={currency}
|
||||||
onChange={(e) => setCurrency(e.target.value)}
|
onChange={(e) => setCurrency(e.target.value)}
|
||||||
@@ -504,7 +598,7 @@ const CardSearch = () => {
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg"
|
className="mt-4 w-full sm:w-auto min-h-[44px] px-6 py-3 bg-blue-600 hover:bg-blue-700 rounded-lg font-medium text-base"
|
||||||
>
|
>
|
||||||
Search
|
Search
|
||||||
</button>
|
</button>
|
||||||
@@ -523,21 +617,110 @@ const CardSearch = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{searchResults && searchResults.length > 0 && (
|
{searchResults && searchResults.length > 0 && (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
|
||||||
{searchResults.map((card) => (
|
{searchResults.map((card) => {
|
||||||
<div key={card.id} className="bg-gray-800 rounded-lg overflow-hidden">
|
const currentFaceIndex = getCurrentFaceIndex(card.id);
|
||||||
<MagicCard card={card} />
|
const isMultiFaced = isDoubleFaced(card);
|
||||||
<div className="p-4">
|
const inCollection = userCollection.get(card.id) || 0;
|
||||||
<h3 className="font-bold mb-2">{card.name}</h3>
|
const isAddingThisCard = addingCardId === card.id;
|
||||||
<p className="text-gray-400 text-sm">{card.type_line}</p>
|
|
||||||
|
const displayName = isMultiFaced && card.card_faces
|
||||||
|
? card.card_faces[currentFaceIndex]?.name || card.name
|
||||||
|
: card.name;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={card.id} className="bg-gray-800 rounded-lg overflow-hidden hover:ring-2 hover:ring-blue-500 transition-all">
|
||||||
|
<div className="relative">
|
||||||
|
{getCardImageUri(card, currentFaceIndex) ? (
|
||||||
|
<img
|
||||||
|
src={getCardImageUri(card, currentFaceIndex)}
|
||||||
|
alt={displayName}
|
||||||
|
className="w-full h-auto"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<MagicCard card={card} />
|
||||||
|
)}
|
||||||
|
{isMultiFaced && (
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggleCardFace(card.id, card.card_faces!.length);
|
||||||
|
}}
|
||||||
|
className="absolute bottom-2 right-2 bg-purple-600 hover:bg-purple-700 text-white p-2 rounded-full shadow-lg transition-all"
|
||||||
|
title="Flip card"
|
||||||
|
>
|
||||||
|
<RefreshCw size={16} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<h3 className="font-bold">{displayName}</h3>
|
||||||
|
{inCollection > 0 && (
|
||||||
|
<span className="text-xs bg-green-600 px-2 py-0.5 rounded-full flex items-center gap-1">
|
||||||
|
<CheckCircle size={12} />
|
||||||
|
x{inCollection}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-gray-400 text-sm mb-3">
|
||||||
|
{isMultiFaced && card.card_faces
|
||||||
|
? card.card_faces[currentFaceIndex]?.type_line || card.type_line
|
||||||
|
: card.type_line}
|
||||||
|
</p>
|
||||||
|
{card.prices?.usd && (
|
||||||
|
<div className="text-sm text-gray-400 mb-2">${card.prices.usd}</div>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => handleAddCardToCollection(card.id)}
|
||||||
|
disabled={isAddingThisCard}
|
||||||
|
className="w-full px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg flex items-center justify-center gap-2"
|
||||||
|
title="Add to collection"
|
||||||
|
>
|
||||||
|
{isAddingThisCard ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="animate-spin" size={20} />
|
||||||
|
Adding...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<PackagePlus size={20} />
|
||||||
|
Add to Collection
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
);
|
||||||
))}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Snackbar */}
|
||||||
|
{snackbar && (
|
||||||
|
<div
|
||||||
|
className={`fixed bottom-4 right-4 p-4 rounded-lg shadow-lg transition-all duration-300 ${
|
||||||
|
snackbar.type === 'success' ? 'bg-green-500' : 'bg-red-500'
|
||||||
|
} text-white z-50`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center">
|
||||||
|
{snackbar.type === 'success' ? (
|
||||||
|
<CheckCircle className="mr-2" size={20} />
|
||||||
|
) : (
|
||||||
|
<XCircle className="mr-2" size={20} />
|
||||||
|
)}
|
||||||
|
<span>{snackbar.message}</span>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => setSnackbar(null)} className="ml-4 text-gray-200 hover:text-white focus:outline-none">
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default CardSearch;
|
export default CardSearch;
|
||||||
|
|||||||
@@ -1,121 +1,500 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Search, Plus } from 'lucide-react';
|
import { Search, Loader2, Trash2, CheckCircle, XCircle, RefreshCw, Plus, Minus, X } from 'lucide-react';
|
||||||
import { Card } from '../types';
|
import { Card } from '../types';
|
||||||
import { searchCards } from '../services/api';
|
import { getUserCollection, getCardsByIds, addCardToCollection } from '../services/api';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
import ConfirmModal from './ConfirmModal';
|
||||||
|
|
||||||
export default function Collection() {
|
export default function Collection() {
|
||||||
|
const { user } = useAuth();
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [searchResults, setSearchResults] = useState<Card[]>([]);
|
|
||||||
const [collection, setCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
const [collection, setCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
||||||
|
const [filteredCollection, setFilteredCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
||||||
|
const [isLoadingCollection, setIsLoadingCollection] = useState(true);
|
||||||
|
const [hoveredCard, setHoveredCard] = useState<Card | null>(null);
|
||||||
|
const [selectedCard, setSelectedCard] = useState<{ card: Card; quantity: number } | null>(null);
|
||||||
|
const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map());
|
||||||
|
const [snackbar, setSnackbar] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
|
||||||
|
const [isUpdating, setIsUpdating] = useState(false);
|
||||||
|
const [confirmModal, setConfirmModal] = useState<{
|
||||||
|
isOpen: boolean;
|
||||||
|
cardId: string;
|
||||||
|
cardName: string;
|
||||||
|
}>({ isOpen: false, cardId: '', cardName: '' });
|
||||||
|
|
||||||
const handleSearch = async (e: React.FormEvent) => {
|
// Helper function to check if a card has an actual back face (not adventure/split/etc)
|
||||||
e.preventDefault();
|
const isDoubleFaced = (card: Card) => {
|
||||||
if (!searchQuery.trim()) return;
|
// Only show flip for cards with physical back sides
|
||||||
|
const backFaceLayouts = ['transform', 'modal_dfc', 'double_faced_token', 'reversible_card'];
|
||||||
try {
|
return card.card_faces && card.card_faces.length > 1 && backFaceLayouts.includes(card.layout);
|
||||||
const cards = await searchCards(searchQuery);
|
|
||||||
setSearchResults(cards);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to search cards:', error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const addToCollection = (card: Card) => {
|
// Helper function to get the current face index for a card
|
||||||
setCollection(prev => {
|
const getCurrentFaceIndex = (cardId: string) => {
|
||||||
const existing = prev.find(c => c.card.id === card.id);
|
return cardFaceIndex.get(cardId) || 0;
|
||||||
if (existing) {
|
};
|
||||||
return prev.map(c =>
|
|
||||||
c.card.id === card.id
|
// Helper function to get the image URI for a card (handling both single and double-faced)
|
||||||
? { ...c, quantity: c.quantity + 1 }
|
const getCardImageUri = (card: Card, faceIndex: number = 0) => {
|
||||||
: c
|
if (isDoubleFaced(card) && card.card_faces) {
|
||||||
);
|
return card.card_faces[faceIndex]?.image_uris?.normal || card.card_faces[faceIndex]?.image_uris?.small;
|
||||||
}
|
}
|
||||||
return [...prev, { card, quantity: 1 }];
|
return card.image_uris?.normal || card.image_uris?.small;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to get the large image URI for hover preview
|
||||||
|
const getCardLargeImageUri = (card: Card, faceIndex: number = 0) => {
|
||||||
|
if (isDoubleFaced(card) && card.card_faces) {
|
||||||
|
return card.card_faces[faceIndex]?.image_uris?.large || card.card_faces[faceIndex]?.image_uris?.normal;
|
||||||
|
}
|
||||||
|
return card.image_uris?.large || card.image_uris?.normal;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Toggle card face
|
||||||
|
const toggleCardFace = (cardId: string, totalFaces: number) => {
|
||||||
|
setCardFaceIndex(prev => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const currentIndex = prev.get(cardId) || 0;
|
||||||
|
const nextIndex = (currentIndex + 1) % totalFaces;
|
||||||
|
newMap.set(cardId, nextIndex);
|
||||||
|
return newMap;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Load user's collection from Supabase on mount
|
||||||
|
useEffect(() => {
|
||||||
|
const loadCollection = async () => {
|
||||||
|
if (!user) {
|
||||||
|
setIsLoadingCollection(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsLoadingCollection(true);
|
||||||
|
// Get collection from Supabase (returns Map<card_id, quantity>)
|
||||||
|
const collectionMap = await getUserCollection(user.id);
|
||||||
|
|
||||||
|
if (collectionMap.size === 0) {
|
||||||
|
setCollection([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the actual card data from Scryfall for all cards in collection
|
||||||
|
const cardIds = Array.from(collectionMap.keys());
|
||||||
|
const cards = await getCardsByIds(cardIds);
|
||||||
|
|
||||||
|
// Combine card data with quantities
|
||||||
|
const collectionWithCards = cards.map(card => ({
|
||||||
|
card,
|
||||||
|
quantity: collectionMap.get(card.id) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
setCollection(collectionWithCards);
|
||||||
|
setFilteredCollection(collectionWithCards);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading collection:', error);
|
||||||
|
setSnackbar({ message: 'Failed to load collection', type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setIsLoadingCollection(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadCollection();
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
// Filter collection based on search query
|
||||||
|
useEffect(() => {
|
||||||
|
if (!searchQuery.trim()) {
|
||||||
|
setFilteredCollection(collection);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const query = searchQuery.toLowerCase();
|
||||||
|
const filtered = collection.filter(({ card }) => {
|
||||||
|
return (
|
||||||
|
card.name.toLowerCase().includes(query) ||
|
||||||
|
card.type_line?.toLowerCase().includes(query) ||
|
||||||
|
card.oracle_text?.toLowerCase().includes(query) ||
|
||||||
|
card.colors?.some(color => color.toLowerCase().includes(query))
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
setFilteredCollection(filtered);
|
||||||
|
}, [searchQuery, collection]);
|
||||||
|
|
||||||
|
// Update card quantity in collection
|
||||||
|
const updateCardQuantity = async (cardId: string, newQuantity: number) => {
|
||||||
|
if (!user || newQuantity < 0) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsUpdating(true);
|
||||||
|
|
||||||
|
if (newQuantity === 0) {
|
||||||
|
// Remove card from collection
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.delete()
|
||||||
|
.eq('user_id', user.id)
|
||||||
|
.eq('card_id', cardId);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
// Update local state
|
||||||
|
setCollection(prev => prev.filter(item => item.card.id !== cardId));
|
||||||
|
setSelectedCard(null);
|
||||||
|
setSnackbar({ message: 'Card removed from collection', type: 'success' });
|
||||||
|
} else {
|
||||||
|
// Update quantity
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.update({ quantity: newQuantity, updated_at: new Date().toISOString() })
|
||||||
|
.eq('user_id', user.id)
|
||||||
|
.eq('card_id', cardId);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
// Update local state
|
||||||
|
setCollection(prev =>
|
||||||
|
prev.map(item =>
|
||||||
|
item.card.id === cardId ? { ...item, quantity: newQuantity } : item
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (selectedCard && selectedCard.card.id === cardId) {
|
||||||
|
setSelectedCard({ ...selectedCard, quantity: newQuantity });
|
||||||
|
}
|
||||||
|
|
||||||
|
setSnackbar({ message: 'Quantity updated', type: 'success' });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating card quantity:', error);
|
||||||
|
setSnackbar({ message: 'Failed to update quantity', type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setIsUpdating(false);
|
||||||
|
setTimeout(() => setSnackbar(null), 3000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add one to quantity
|
||||||
|
const incrementQuantity = async (cardId: string, currentQuantity: number) => {
|
||||||
|
await updateCardQuantity(cardId, currentQuantity + 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Remove one from quantity
|
||||||
|
const decrementQuantity = async (cardId: string, currentQuantity: number) => {
|
||||||
|
if (currentQuantity > 0) {
|
||||||
|
await updateCardQuantity(cardId, currentQuantity - 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 text-white p-6">
|
<div className="bg-gray-900 text-white p-3 sm:p-6">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<h1 className="text-3xl font-bold mb-6">My Collection</h1>
|
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">My Collection</h1>
|
||||||
|
|
||||||
{/* Search */}
|
{/* Search within collection */}
|
||||||
<form onSubmit={handleSearch} className="flex gap-2 mb-8">
|
<div className="mb-8">
|
||||||
<div className="relative flex-1">
|
<div className="relative">
|
||||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
placeholder="Search cards to add..."
|
placeholder="Search your collection by name, type, or text..."
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<button
|
</div>
|
||||||
type="submit"
|
|
||||||
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<Search size={20} />
|
|
||||||
Search
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{/* Search Results */}
|
|
||||||
{searchResults.length > 0 && (
|
|
||||||
<div className="mb-8">
|
|
||||||
<h2 className="text-xl font-semibold mb-4">Search Results</h2>
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
|
||||||
{searchResults.map(card => (
|
|
||||||
<div key={card.id} className="bg-gray-800 rounded-lg overflow-hidden">
|
|
||||||
{card.image_uris?.normal && (
|
|
||||||
<img
|
|
||||||
src={card.image_uris.normal}
|
|
||||||
alt={card.name}
|
|
||||||
className="w-full h-auto"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<div className="p-4">
|
|
||||||
<h3 className="font-bold mb-2">{card.name}</h3>
|
|
||||||
<button
|
|
||||||
onClick={() => addToCollection(card)}
|
|
||||||
className="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center justify-center gap-2"
|
|
||||||
>
|
|
||||||
<Plus size={20} />
|
|
||||||
Add to Collection
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Collection */}
|
{/* Collection */}
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-xl font-semibold mb-4">My Cards</h2>
|
<h2 className="text-xl font-semibold mb-4">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`}
|
||||||
{collection.map(({ card, quantity }) => (
|
</h2>
|
||||||
<div key={card.id} className="bg-gray-800 rounded-lg overflow-hidden">
|
|
||||||
{card.image_uris?.normal && (
|
{isLoadingCollection ? (
|
||||||
<img
|
<div className="flex items-center justify-center py-12">
|
||||||
src={card.image_uris.normal}
|
<Loader2 className="animate-spin text-blue-500" size={48} />
|
||||||
alt={card.name}
|
</div>
|
||||||
className="w-full h-auto"
|
) : collection.length === 0 ? (
|
||||||
/>
|
<div className="text-center py-12 text-gray-400">
|
||||||
|
<p className="text-lg mb-2">Your collection is empty</p>
|
||||||
|
<p className="text-sm">Add cards from the Deck Manager to build your collection</p>
|
||||||
|
</div>
|
||||||
|
) : filteredCollection.length === 0 ? (
|
||||||
|
<div className="text-center py-12 text-gray-400">
|
||||||
|
<p className="text-lg mb-2">No cards found</p>
|
||||||
|
<p className="text-sm">Try a different search term</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-7 xl:grid-cols-9 gap-2 sm:gap-3">
|
||||||
|
{filteredCollection.map(({ card, quantity }) => {
|
||||||
|
const currentFaceIndex = getCurrentFaceIndex(card.id);
|
||||||
|
const isMultiFaced = isDoubleFaced(card);
|
||||||
|
const displayName = isMultiFaced && card.card_faces
|
||||||
|
? card.card_faces[currentFaceIndex]?.name || card.name
|
||||||
|
: card.name;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={card.id}
|
||||||
|
className="relative group cursor-pointer"
|
||||||
|
onMouseEnter={() => setHoveredCard(card)}
|
||||||
|
onMouseLeave={() => setHoveredCard(null)}
|
||||||
|
onClick={() => setSelectedCard({ card, quantity })}
|
||||||
|
>
|
||||||
|
{/* Small card thumbnail */}
|
||||||
|
<div className="relative rounded-lg overflow-hidden shadow-lg transition-all group-hover:ring-2 group-hover:ring-blue-500">
|
||||||
|
<img
|
||||||
|
src={getCardImageUri(card, currentFaceIndex)}
|
||||||
|
alt={displayName}
|
||||||
|
className="w-full h-auto"
|
||||||
|
/>
|
||||||
|
{/* Quantity badge */}
|
||||||
|
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs sm:text-sm font-bold px-2 py-1 rounded-full shadow-lg">
|
||||||
|
x{quantity}
|
||||||
|
</div>
|
||||||
|
{/* Flip button for double-faced cards */}
|
||||||
|
{isMultiFaced && (
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggleCardFace(card.id, card.card_faces!.length);
|
||||||
|
}}
|
||||||
|
className="absolute bottom-1 right-1 bg-purple-600 hover:bg-purple-700 text-white p-1 rounded-full shadow-lg transition-all"
|
||||||
|
title="Flip card"
|
||||||
|
>
|
||||||
|
<RefreshCw size={12} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Card name below thumbnail */}
|
||||||
|
<div className="mt-1 text-xs text-center truncate px-1">
|
||||||
|
{displayName}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Hover Card Preview - only show if no card is selected */}
|
||||||
|
{hoveredCard && !selectedCard && (() => {
|
||||||
|
const currentFaceIndex = getCurrentFaceIndex(hoveredCard.id);
|
||||||
|
const isMultiFaced = isDoubleFaced(hoveredCard);
|
||||||
|
const currentFace = isMultiFaced && hoveredCard.card_faces
|
||||||
|
? hoveredCard.card_faces[currentFaceIndex]
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const displayName = currentFace?.name || hoveredCard.name;
|
||||||
|
const displayTypeLine = currentFace?.type_line || hoveredCard.type_line;
|
||||||
|
const displayOracleText = currentFace?.oracle_text || hoveredCard.oracle_text;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="hidden lg:block fixed top-1/2 right-8 transform -translate-y-1/2 z-40 pointer-events-none">
|
||||||
|
<div className="bg-gray-800 rounded-lg shadow-2xl p-4 max-w-md">
|
||||||
|
<div className="relative">
|
||||||
|
<img
|
||||||
|
src={getCardLargeImageUri(hoveredCard, currentFaceIndex)}
|
||||||
|
alt={displayName}
|
||||||
|
className="w-full h-auto rounded-lg shadow-lg"
|
||||||
|
/>
|
||||||
|
{isMultiFaced && (
|
||||||
|
<div className="absolute top-2 right-2 bg-purple-600 text-white text-xs font-bold px-2 py-1 rounded-full shadow-lg">
|
||||||
|
Face {currentFaceIndex + 1}/{hoveredCard.card_faces!.length}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="p-4">
|
</div>
|
||||||
<div className="flex justify-between items-center mb-2">
|
<div className="mt-3 space-y-2">
|
||||||
<h3 className="font-bold">{card.name}</h3>
|
<h3 className="text-xl font-bold">{displayName}</h3>
|
||||||
<span className="text-sm bg-blue-600 px-2 py-1 rounded">
|
<p className="text-sm text-gray-400">{displayTypeLine}</p>
|
||||||
x{quantity}
|
{displayOracleText && (
|
||||||
</span>
|
<p className="text-sm text-gray-300 border-t border-gray-700 pt-2">
|
||||||
|
{displayOracleText}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{hoveredCard.prices?.usd && (
|
||||||
|
<div className="text-sm text-green-400 font-semibold border-t border-gray-700 pt-2">
|
||||||
|
${hoveredCard.prices.usd}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{/* Card Detail Panel - slides in from right */}
|
||||||
|
{selectedCard && (() => {
|
||||||
|
const currentFaceIndex = getCurrentFaceIndex(selectedCard.card.id);
|
||||||
|
const isMultiFaced = isDoubleFaced(selectedCard.card);
|
||||||
|
const currentFace = isMultiFaced && selectedCard.card.card_faces
|
||||||
|
? selectedCard.card.card_faces[currentFaceIndex]
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const displayName = currentFace?.name || selectedCard.card.name;
|
||||||
|
const displayTypeLine = currentFace?.type_line || selectedCard.card.type_line;
|
||||||
|
const displayOracleText = currentFace?.oracle_text || selectedCard.card.oracle_text;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Backdrop */}
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300"
|
||||||
|
onClick={() => setSelectedCard(null)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Sliding Panel */}
|
||||||
|
<div className="fixed top-0 right-0 h-full w-full md:w-96 bg-gray-800 shadow-2xl z-50 overflow-y-auto animate-slide-in-right">
|
||||||
|
{/* Close button - fixed position, stays visible when scrolling */}
|
||||||
|
<button
|
||||||
|
onClick={() => setSelectedCard(null)}
|
||||||
|
className="fixed top-4 right-4 bg-gray-700 hover:bg-gray-600 text-white p-2 md:p-1.5 rounded-full transition-colors z-[60] shadow-lg"
|
||||||
|
aria-label="Close"
|
||||||
|
>
|
||||||
|
<X size={24} className="md:w-5 md:h-5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="p-4 sm:p-6">
|
||||||
|
|
||||||
|
{/* Card Image */}
|
||||||
|
<div className="relative mb-4">
|
||||||
|
<img
|
||||||
|
src={getCardLargeImageUri(selectedCard.card, currentFaceIndex)}
|
||||||
|
alt={displayName}
|
||||||
|
className="w-full h-auto rounded-lg shadow-lg"
|
||||||
|
/>
|
||||||
|
{isMultiFaced && (
|
||||||
|
<>
|
||||||
|
<div className="absolute top-2 right-2 bg-purple-600 text-white text-xs font-bold px-2 py-1 rounded-full shadow-lg">
|
||||||
|
Face {currentFaceIndex + 1}/{selectedCard.card.card_faces!.length}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => toggleCardFace(selectedCard.card.id, selectedCard.card.card_faces!.length)}
|
||||||
|
className="absolute bottom-2 right-2 bg-purple-600 hover:bg-purple-700 text-white p-2 rounded-full shadow-lg transition-all"
|
||||||
|
title="Flip card"
|
||||||
|
>
|
||||||
|
<RefreshCw size={20} />
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Card Info */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl md:text-2xl font-bold text-white mb-2">{displayName}</h2>
|
||||||
|
<p className="text-xs sm:text-sm text-gray-400">{displayTypeLine}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{displayOracleText && (
|
||||||
|
<div className="border-t border-gray-700 pt-3">
|
||||||
|
<p className="text-sm text-gray-300">{displayOracleText}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedCard.card.prices?.usd && (
|
||||||
|
<div className="border-t border-gray-700 pt-3">
|
||||||
|
<div className="text-lg text-green-400 font-semibold">
|
||||||
|
${selectedCard.card.prices.usd} each
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-gray-400">
|
||||||
|
Total value: ${(parseFloat(selectedCard.card.prices.usd) * selectedCard.quantity).toFixed(2)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Quantity Management */}
|
||||||
|
<div className="border-t border-gray-700 pt-3">
|
||||||
|
<h3 className="text-lg font-semibold mb-3">Quantity in Collection</h3>
|
||||||
|
<div className="flex items-center justify-between bg-gray-900 rounded-lg p-4">
|
||||||
|
<button
|
||||||
|
onClick={() => decrementQuantity(selectedCard.card.id, selectedCard.quantity)}
|
||||||
|
disabled={isUpdating || selectedCard.quantity === 0}
|
||||||
|
className="bg-red-600 hover:bg-red-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white p-2 rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
<Minus size={20} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="text-3xl font-bold">{selectedCard.quantity}</div>
|
||||||
|
<div className="text-xs text-gray-400">copies</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => incrementQuantity(selectedCard.card.id, selectedCard.quantity)}
|
||||||
|
disabled={isUpdating}
|
||||||
|
className="bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white p-2 rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
<Plus size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Remove from collection button */}
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setConfirmModal({
|
||||||
|
isOpen: true,
|
||||||
|
cardId: selectedCard.card.id,
|
||||||
|
cardName: displayName,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
disabled={isUpdating}
|
||||||
|
className="w-full mt-3 min-h-[44px] px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg flex items-center justify-center gap-2 transition-colors"
|
||||||
|
>
|
||||||
|
<Trash2 size={20} />
|
||||||
|
Remove from Collection
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{/* Confirm Modal */}
|
||||||
|
<ConfirmModal
|
||||||
|
isOpen={confirmModal.isOpen}
|
||||||
|
onClose={() => setConfirmModal({ isOpen: false, cardId: '', cardName: '' })}
|
||||||
|
onConfirm={() => {
|
||||||
|
updateCardQuantity(confirmModal.cardId, 0);
|
||||||
|
setConfirmModal({ isOpen: false, cardId: '', cardName: '' });
|
||||||
|
}}
|
||||||
|
title="Remove from Collection"
|
||||||
|
message={`Are you sure you want to remove "${confirmModal.cardName}" from your collection? This action cannot be undone.`}
|
||||||
|
confirmText="Remove"
|
||||||
|
cancelText="Cancel"
|
||||||
|
variant="danger"
|
||||||
|
isLoading={isUpdating}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Snackbar */}
|
||||||
|
{snackbar && (
|
||||||
|
<div
|
||||||
|
className={`fixed bottom-4 right-4 p-4 rounded-lg shadow-lg transition-all duration-300 ${
|
||||||
|
snackbar.type === 'success' ? 'bg-green-500' : 'bg-red-500'
|
||||||
|
} text-white z-50`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center">
|
||||||
|
{snackbar.type === 'success' ? (
|
||||||
|
<CheckCircle className="mr-2" size={20} />
|
||||||
|
) : (
|
||||||
|
<XCircle className="mr-2" size={20} />
|
||||||
|
)}
|
||||||
|
<span>{snackbar.message}</span>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => setSnackbar(null)} className="ml-4 text-gray-200 hover:text-white focus:outline-none">
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
305
src/components/Community.tsx
Normal file
305
src/components/Community.tsx
Normal file
@@ -0,0 +1,305 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2 } from 'lucide-react';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
import { getFriends, Friend } from '../services/friendsService';
|
||||||
|
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||||
|
import { Card } from '../types';
|
||||||
|
import TradeCreator from './TradeCreator';
|
||||||
|
|
||||||
|
interface UserProfile {
|
||||||
|
id: string;
|
||||||
|
username: string | null;
|
||||||
|
collection_visibility: 'public' | 'friends' | 'private' | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CollectionItem {
|
||||||
|
card: Card;
|
||||||
|
quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Tab = 'public' | 'friends';
|
||||||
|
|
||||||
|
export default function Community() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [activeTab, setActiveTab] = useState<Tab>('public');
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [publicUsers, setPublicUsers] = useState<UserProfile[]>([]);
|
||||||
|
const [friends, setFriends] = useState<Friend[]>([]);
|
||||||
|
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
|
||||||
|
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [loadingCollection, setLoadingCollection] = useState(false);
|
||||||
|
const [showTradeCreator, setShowTradeCreator] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
loadData();
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [publicData, friendsData] = await Promise.all([
|
||||||
|
loadPublicUsers(),
|
||||||
|
getFriends(user.id),
|
||||||
|
]);
|
||||||
|
setPublicUsers(publicData);
|
||||||
|
setFriends(friendsData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading community data:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadPublicUsers = async (): Promise<UserProfile[]> => {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('profiles')
|
||||||
|
.select('id, username, collection_visibility')
|
||||||
|
.eq('collection_visibility', 'public')
|
||||||
|
.neq('id', user?.id)
|
||||||
|
.order('username');
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data || [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadUserCollection = async (userId: string) => {
|
||||||
|
setLoadingCollection(true);
|
||||||
|
try {
|
||||||
|
const collectionMap = await getUserCollection(userId);
|
||||||
|
|
||||||
|
if (collectionMap.size === 0) {
|
||||||
|
setSelectedUserCollection([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cardIds = Array.from(collectionMap.keys());
|
||||||
|
const cards = await getCardsByIds(cardIds);
|
||||||
|
|
||||||
|
const collectionWithCards = cards.map((card) => ({
|
||||||
|
card,
|
||||||
|
quantity: collectionMap.get(card.id) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
setSelectedUserCollection(collectionWithCards);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading collection:', error);
|
||||||
|
setSelectedUserCollection([]);
|
||||||
|
} finally {
|
||||||
|
setLoadingCollection(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleViewCollection = async (userProfile: UserProfile) => {
|
||||||
|
setSelectedUser(userProfile);
|
||||||
|
await loadUserCollection(userProfile.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const filteredPublicUsers = publicUsers.filter(
|
||||||
|
(u) => !searchQuery || u.username?.toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
const friendProfiles: UserProfile[] = friends.map((f) => ({
|
||||||
|
id: f.id,
|
||||||
|
username: f.username,
|
||||||
|
collection_visibility: 'friends' as const,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const filteredFriends = friendProfiles.filter(
|
||||||
|
(f) => !searchQuery || f.username?.toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
|
||||||
|
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If viewing a user's collection
|
||||||
|
if (selectedUser) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-900 text-white p-6">
|
||||||
|
<div className="max-w-7xl mx-auto">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedUser(null);
|
||||||
|
setSelectedUserCollection([]);
|
||||||
|
}}
|
||||||
|
className="text-blue-400 hover:text-blue-300 mb-2"
|
||||||
|
>
|
||||||
|
← Back to Community
|
||||||
|
</button>
|
||||||
|
<h1 className="text-3xl font-bold">{selectedUser.username}'s Collection</h1>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowTradeCreator(true)}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition"
|
||||||
|
>
|
||||||
|
<ArrowLeftRight size={20} />
|
||||||
|
Propose Trade
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Collection Grid */}
|
||||||
|
{loadingCollection ? (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="animate-spin text-blue-500" size={48} />
|
||||||
|
</div>
|
||||||
|
) : selectedUserCollection.length === 0 ? (
|
||||||
|
<p className="text-gray-400 text-center py-12">This collection is empty</p>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-7 xl:grid-cols-9 gap-2 sm:gap-3">
|
||||||
|
{selectedUserCollection.map(({ card, quantity }) => (
|
||||||
|
<div key={card.id} className="relative group">
|
||||||
|
<div className="rounded-lg overflow-hidden shadow-lg">
|
||||||
|
<img
|
||||||
|
src={card.image_uris?.normal || card.image_uris?.small}
|
||||||
|
alt={card.name}
|
||||||
|
className="w-full h-auto"
|
||||||
|
/>
|
||||||
|
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs font-bold px-2 py-1 rounded-full">
|
||||||
|
x{quantity}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-xs text-center truncate px-1">{card.name}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Trade Creator Modal */}
|
||||||
|
{showTradeCreator && (
|
||||||
|
<TradeCreator
|
||||||
|
receiverId={selectedUser.id}
|
||||||
|
receiverUsername={selectedUser.username || 'Unknown'}
|
||||||
|
receiverCollection={selectedUserCollection}
|
||||||
|
onClose={() => setShowTradeCreator(false)}
|
||||||
|
onTradeCreated={() => {
|
||||||
|
setShowTradeCreator(false);
|
||||||
|
alert('Trade proposal sent!');
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-900 text-white p-6">
|
||||||
|
<div className="max-w-4xl mx-auto">
|
||||||
|
<h1 className="text-3xl font-bold mb-6">Community</h1>
|
||||||
|
|
||||||
|
{/* Search */}
|
||||||
|
<div className="relative mb-6">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
placeholder="Search users..."
|
||||||
|
className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex gap-2 mb-6">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('public')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||||
|
activeTab === 'public'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Globe size={18} />
|
||||||
|
Public Collections ({filteredPublicUsers.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('friends')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||||
|
activeTab === 'friends'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Users size={18} />
|
||||||
|
Friends ({filteredFriends.length})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* User List */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
{activeTab === 'public' && (
|
||||||
|
<>
|
||||||
|
{filteredPublicUsers.length === 0 ? (
|
||||||
|
<p className="text-gray-400 text-center py-8">
|
||||||
|
No public collections found
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
filteredPublicUsers.map((userProfile) => (
|
||||||
|
<div
|
||||||
|
key={userProfile.id}
|
||||||
|
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Globe size={20} className="text-green-400" />
|
||||||
|
<span className="font-medium">{userProfile.username || 'Unknown'}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleViewCollection(userProfile)}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
|
||||||
|
>
|
||||||
|
<Eye size={16} />
|
||||||
|
View Collection
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'friends' && (
|
||||||
|
<>
|
||||||
|
{filteredFriends.length === 0 ? (
|
||||||
|
<p className="text-gray-400 text-center py-8">
|
||||||
|
{friends.length === 0
|
||||||
|
? 'Add friends to see their collections'
|
||||||
|
: 'No friends match your search'}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
filteredFriends.map((friend) => (
|
||||||
|
<div
|
||||||
|
key={friend.id}
|
||||||
|
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Users size={20} className="text-blue-400" />
|
||||||
|
<span className="font-medium">{friend.username || 'Unknown'}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleViewCollection(friend)}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
|
||||||
|
>
|
||||||
|
<Eye size={16} />
|
||||||
|
View Collection
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
105
src/components/ConfirmModal.tsx
Normal file
105
src/components/ConfirmModal.tsx
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { AlertCircle, CheckCircle, Trash2, AlertTriangle } from 'lucide-react';
|
||||||
|
import Modal from './Modal';
|
||||||
|
|
||||||
|
interface ConfirmModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onConfirm: () => void;
|
||||||
|
title: string;
|
||||||
|
message: string;
|
||||||
|
confirmText?: string;
|
||||||
|
cancelText?: string;
|
||||||
|
variant?: 'danger' | 'warning' | 'info' | 'success';
|
||||||
|
isLoading?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ConfirmModal({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
onConfirm,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
confirmText = 'Confirm',
|
||||||
|
cancelText = 'Cancel',
|
||||||
|
variant = 'danger',
|
||||||
|
isLoading = false,
|
||||||
|
}: ConfirmModalProps) {
|
||||||
|
const handleConfirm = () => {
|
||||||
|
onConfirm();
|
||||||
|
if (!isLoading) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const variantConfig = {
|
||||||
|
danger: {
|
||||||
|
icon: Trash2,
|
||||||
|
iconColor: 'text-red-500',
|
||||||
|
iconBg: 'bg-red-500/10',
|
||||||
|
buttonColor: 'bg-red-600 hover:bg-red-700',
|
||||||
|
},
|
||||||
|
warning: {
|
||||||
|
icon: AlertTriangle,
|
||||||
|
iconColor: 'text-yellow-500',
|
||||||
|
iconBg: 'bg-yellow-500/10',
|
||||||
|
buttonColor: 'bg-yellow-600 hover:bg-yellow-700',
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
icon: AlertCircle,
|
||||||
|
iconColor: 'text-blue-500',
|
||||||
|
iconBg: 'bg-blue-500/10',
|
||||||
|
buttonColor: 'bg-blue-600 hover:bg-blue-700',
|
||||||
|
},
|
||||||
|
success: {
|
||||||
|
icon: CheckCircle,
|
||||||
|
iconColor: 'text-green-500',
|
||||||
|
iconBg: 'bg-green-500/10',
|
||||||
|
buttonColor: 'bg-green-600 hover:bg-green-700',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const config = variantConfig[variant];
|
||||||
|
const Icon = config.icon;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal isOpen={isOpen} onClose={onClose} size="sm" showCloseButton={false}>
|
||||||
|
<div className="p-6">
|
||||||
|
{/* Icon */}
|
||||||
|
<div className="flex items-center justify-center mb-4">
|
||||||
|
<div className={`${config.iconBg} p-3 rounded-full`}>
|
||||||
|
<Icon className={config.iconColor} size={32} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Title */}
|
||||||
|
<h2 className="text-xl font-bold text-white text-center mb-2">
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
{/* Message */}
|
||||||
|
<p className="text-gray-400 text-center mb-6">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Buttons */}
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="flex-1 px-4 py-2 bg-gray-700 hover:bg-gray-600 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
{cancelText}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleConfirm}
|
||||||
|
disabled={isLoading}
|
||||||
|
className={`flex-1 px-4 py-2 ${config.buttonColor} disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg transition-colors`}
|
||||||
|
>
|
||||||
|
{isLoading ? 'Loading...' : confirmText}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -22,55 +22,52 @@ export default function DeckCard({ deck, onEdit }: DeckCardProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="bg-gray-800 rounded-xl overflow-hidden shadow-lg card-hover cursor-pointer animate-scale-in"
|
className="bg-gray-800 rounded-lg overflow-hidden shadow-lg hover:shadow-xl transition-all cursor-pointer group"
|
||||||
onClick={() => onEdit?.(deck.id)}
|
onClick={() => onEdit?.(deck.id)}
|
||||||
>
|
>
|
||||||
<div className="relative h-48 overflow-hidden">
|
{/* Full Card Art */}
|
||||||
|
<div className="relative aspect-[5/7] overflow-hidden">
|
||||||
<img
|
<img
|
||||||
src={commander?.image_uris?.normal || deck.cards[0]?.card.image_uris?.normal}
|
src={commander?.image_uris?.normal || deck.cards[0]?.card.image_uris?.normal}
|
||||||
alt={commander?.name || deck.cards[0]?.card.name}
|
alt={commander?.name || deck.cards[0]?.card.name}
|
||||||
className="w-full object-cover object-top transform translate-y-[-12%]"
|
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||||
/>
|
/>
|
||||||
<div className="absolute inset-0 bg-gradient-to-t from-gray-900 to-transparent" />
|
{/* Overlay for text readability */}
|
||||||
</div>
|
<div className="absolute inset-0 bg-gradient-to-t from-gray-900 via-gray-900/60 to-transparent" />
|
||||||
|
|
||||||
<div className="p-4">
|
{/* Deck info overlay */}
|
||||||
<div className="flex items-center justify-between mb-2">
|
<div className="absolute bottom-0 left-0 right-0 p-3">
|
||||||
<h3 className="text-xl font-bold text-white">{deck.name}</h3>
|
<div className="flex items-start justify-between mb-1">
|
||||||
{validation.isValid ? (
|
<h3 className="text-base sm:text-lg font-bold text-white line-clamp-2 flex-1">{deck.name}</h3>
|
||||||
<div className="flex items-center text-green-400">
|
{validation.isValid ? (
|
||||||
<Check size={16} className="mr-1" />
|
<Check size={16} className="text-green-400 ml-2 flex-shrink-0" />
|
||||||
<span className="text-sm">Legal</span>
|
) : (
|
||||||
</div>
|
<AlertTriangle size={16} className="text-yellow-400 ml-2 flex-shrink-0" title={validation.errors.join(', ')} />
|
||||||
) : (
|
)}
|
||||||
<div className="flex items-center text-yellow-400" title={validation.errors.join(', ')}>
|
</div>
|
||||||
<AlertTriangle size={16} className="mr-1" />
|
|
||||||
<span className="text-sm">Issues</span>
|
<div className="flex items-center justify-between text-xs text-gray-300 mb-2">
|
||||||
|
<span className="capitalize">{deck.format}</span>
|
||||||
|
<span>{deck.cards.reduce((acc, curr) => acc + curr.quantity, 0)} cards</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{commander && (
|
||||||
|
<div className="text-xs text-blue-300 mb-2 truncate">
|
||||||
|
<span className="font-semibold">Commander:</span> {commander.name}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between text-sm text-gray-400">
|
|
||||||
<span className="capitalize">{deck.format}</span>
|
|
||||||
<span>{deck.cards.reduce((acc, curr) => acc + curr.quantity, 0)} cards</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{commander && (
|
|
||||||
<div className="mt-2 text-sm text-gray-300">
|
|
||||||
<span className="text-blue-400">Commander:</span> {commander.name}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
onEdit?.(deck.id);
|
onEdit?.(deck.id);
|
||||||
}}
|
}}
|
||||||
className="mt-4 w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center justify-center gap-2 text-white btn-ripple transition-smooth glow-on-hover"
|
className="w-full min-h-[36px] px-3 py-2 bg-blue-600/90 hover:bg-blue-600 rounded-md flex items-center justify-center gap-2 text-white text-sm font-medium transition-colors backdrop-blur-sm"
|
||||||
>
|
>
|
||||||
<Edit size={20} />
|
<Edit size={16} />
|
||||||
Edit Deck
|
<span>Edit</span>
|
||||||
</button>
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ import { getCardById, getCardsByIds } from '../services/api';
|
|||||||
import { Deck } from '../types';
|
import { Deck } from '../types';
|
||||||
import { supabase } from "../lib/supabase";
|
import { supabase } from "../lib/supabase";
|
||||||
import DeckCard from "./DeckCard";
|
import DeckCard from "./DeckCard";
|
||||||
|
import { PlusCircle } from 'lucide-react';
|
||||||
|
|
||||||
interface DeckListProps {
|
interface DeckListProps {
|
||||||
onDeckEdit?: (deckId: string) => void;
|
onDeckEdit?: (deckId: string) => void;
|
||||||
|
onCreateDeck?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DeckList = ({ onDeckEdit }: DeckListProps) => {
|
const DeckList = ({ onDeckEdit, onCreateDeck }: DeckListProps) => {
|
||||||
const [decks, setDecks] = useState<Deck[]>([]);
|
const [decks, setDecks] = useState<Deck[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
@@ -88,10 +90,26 @@ const DeckList = ({ onDeckEdit }: DeckListProps) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3 sm:gap-4">
|
||||||
{decks.map((deck) => (
|
{decks.map((deck) => (
|
||||||
<DeckCard key={deck.id} deck={deck} onEdit={onDeckEdit} />
|
<DeckCard key={deck.id} deck={deck} onEdit={onDeckEdit} />
|
||||||
))}
|
))}
|
||||||
|
|
||||||
|
{/* Create New Deck Card */}
|
||||||
|
<button
|
||||||
|
onClick={onCreateDeck}
|
||||||
|
className="bg-gray-800 rounded-lg overflow-hidden shadow-lg hover:shadow-xl border-2 border-dashed border-gray-600 hover:border-blue-500 transition-all duration-300 hover:scale-105 cursor-pointer group aspect-[5/7] flex flex-col items-center justify-center gap-3 p-4"
|
||||||
|
>
|
||||||
|
<PlusCircle size={48} className="text-gray-600 group-hover:text-blue-500 transition-colors" />
|
||||||
|
<div className="text-center">
|
||||||
|
<h3 className="text-sm sm:text-base font-bold text-gray-400 group-hover:text-blue-400 transition-colors">
|
||||||
|
Create New Deck
|
||||||
|
</h3>
|
||||||
|
<p className="text-xs text-gray-500 mt-1 hidden sm:block">
|
||||||
|
Start building
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,49 +1,45 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Plus, Search, Save, Trash2, Upload, Loader2, CheckCircle, XCircle } from 'lucide-react';
|
import { Plus, Minus, Search, Save, Trash2, Loader2, CheckCircle, XCircle, AlertCircle, PackagePlus, RefreshCw } from 'lucide-react';
|
||||||
import { Card, Deck } from '../types';
|
import { Card, Deck } from '../types';
|
||||||
import { searchCards } from '../services/api';
|
import { searchCards, getUserCollection, addCardToCollection, addMultipleCardsToCollection } from '../services/api';
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import { supabase } from '../lib/supabase';
|
import { supabase } from '../lib/supabase';
|
||||||
import { validateDeck } from '../utils/deckValidation';
|
import { validateDeck } from '../utils/deckValidation';
|
||||||
import MagicCard from './MagicCard';
|
import MagicCard from './MagicCard';
|
||||||
|
import { ManaCost } from './ManaCost';
|
||||||
|
|
||||||
interface DeckManagerProps {
|
interface DeckManagerProps {
|
||||||
initialDeck?: Deck;
|
initialDeck?: Deck;
|
||||||
onSave?: () => void;
|
onSave?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const calculateManaCurve = (cards: { card; quantity: number }[]) => {
|
// const calculateManaCurve = (cards: { card; quantity: number }[]) => {
|
||||||
const manaValues = cards.map(({ card }) => {
|
// const manaValues = cards.map(({ card }) => {
|
||||||
if (!card.mana_cost) return 0;
|
// if (!card.mana_cost) return 0;
|
||||||
// Basic heuristic: count mana symbols
|
// // Basic heuristic: count mana symbols
|
||||||
return (card.mana_cost.match(/\{WUBRG0-9]\}/g) || []).length;
|
// return (card.mana_cost.match(/\{WUBRG0-9]\}/g) || []).length;
|
||||||
});
|
// });
|
||||||
|
|
||||||
const averageManaValue = manaValues.reduce((a, b) => a + b, 0) / manaValues.length;
|
// const averageManaValue = manaValues.reduce((a, b) => a + b, 0) / manaValues.length;
|
||||||
return averageManaValue;
|
// return averageManaValue;
|
||||||
};
|
// };
|
||||||
|
|
||||||
const suggestLandCountAndDistribution = (
|
const suggestLandCountAndDistribution = (
|
||||||
cards: { card; quantity: number }[],
|
cards: { card; quantity: number }[],
|
||||||
format: string
|
format: string
|
||||||
) => {
|
) => {
|
||||||
const formatRules = {
|
const formatRules = {
|
||||||
standard: { minCards: 60, targetLands: 24.5 },
|
standard: { minCards: 60 },
|
||||||
modern: { minCards: 60, targetLands: 24.5 },
|
modern: { minCards: 60 },
|
||||||
commander: { minCards: 100, targetLands: 36.5 },
|
commander: { minCards: 100 },
|
||||||
legacy: { minCards: 60, targetLands: 24.5 },
|
legacy: { minCards: 60 },
|
||||||
vintage: { minCards: 60, targetLands: 24.5 },
|
vintage: { minCards: 60 },
|
||||||
pauper: { minCards: 60, targetLands: 24.5 },
|
pauper: { minCards: 60 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const { minCards, targetLands } =
|
const { minCards } =
|
||||||
formatRules[format as keyof typeof formatRules] || formatRules.standard;
|
formatRules[format as keyof typeof formatRules] || formatRules.standard;
|
||||||
const deckSize = cards.reduce((acc, { quantity }) => acc + quantity, 0);
|
const deckSize = cards.reduce((acc, { quantity }) => acc + quantity, 0);
|
||||||
const nonLandCards = cards.reduce(
|
|
||||||
(acc, { card, quantity }) =>
|
|
||||||
card.type_line?.toLowerCase().includes('land') ? acc : acc + quantity,
|
|
||||||
0
|
|
||||||
);
|
|
||||||
const landsToAdd = Math.max(0, minCards - deckSize);
|
const landsToAdd = Math.max(0, minCards - deckSize);
|
||||||
|
|
||||||
const colorCounts = { W: 0, U: 0, B: 0, R: 0, G: 0 };
|
const colorCounts = { W: 0, U: 0, B: 0, R: 0, G: 0 };
|
||||||
@@ -77,7 +73,7 @@ const suggestLandCountAndDistribution = (
|
|||||||
landDistribution[color] = Math.round(landsToAdd * proportion);
|
landDistribution[color] = Math.round(landsToAdd * proportion);
|
||||||
}
|
}
|
||||||
|
|
||||||
let totalDistributed = Object.values(landDistribution).reduce(
|
const totalDistributed = Object.values(landDistribution).reduce(
|
||||||
(acc, count) => acc + count,
|
(acc, count) => acc + count,
|
||||||
0
|
0
|
||||||
);
|
);
|
||||||
@@ -101,6 +97,7 @@ const suggestLandCountAndDistribution = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
||||||
|
const [currentDeckId, setCurrentDeckId] = useState<string | null>(initialDeck?.id || null);
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [searchResults, setSearchResults] = useState<Card[]>([]);
|
const [searchResults, setSearchResults] = useState<Card[]>([]);
|
||||||
const [selectedCards, setSelectedCards] = useState<{
|
const [selectedCards, setSelectedCards] = useState<{
|
||||||
@@ -120,6 +117,147 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [snackbar, setSnackbar] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
|
const [snackbar, setSnackbar] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
|
||||||
|
|
||||||
|
// Collection management state
|
||||||
|
const [userCollection, setUserCollection] = useState<Map<string, number>>(new Map());
|
||||||
|
const [isLoadingCollection, setIsLoadingCollection] = useState(true);
|
||||||
|
const [addingCardId, setAddingCardId] = useState<string | null>(null);
|
||||||
|
const [isAddingAll, setIsAddingAll] = useState(false);
|
||||||
|
const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map());
|
||||||
|
|
||||||
|
// Load user collection on component mount
|
||||||
|
useEffect(() => {
|
||||||
|
const loadUserCollection = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsLoadingCollection(true);
|
||||||
|
const collection = await getUserCollection(user.id);
|
||||||
|
setUserCollection(collection);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading user collection:', error);
|
||||||
|
setSnackbar({ message: 'Failed to load collection', type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setIsLoadingCollection(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadUserCollection();
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
// Helper functions for double-faced cards
|
||||||
|
const isDoubleFaced = (card: Card) => {
|
||||||
|
const backFaceLayouts = ['transform', 'modal_dfc', 'double_faced_token', 'reversible_card'];
|
||||||
|
return card.card_faces && card.card_faces.length > 1 && backFaceLayouts.includes(card.layout);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getCurrentFaceIndex = (cardId: string) => {
|
||||||
|
return cardFaceIndex.get(cardId) || 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleCardFace = (cardId: string, totalFaces: number) => {
|
||||||
|
setCardFaceIndex(prev => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const currentIndex = prev.get(cardId) || 0;
|
||||||
|
const nextIndex = (currentIndex + 1) % totalFaces;
|
||||||
|
newMap.set(cardId, nextIndex);
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const getCardImageUri = (card: Card, faceIndex: number = 0) => {
|
||||||
|
if (isDoubleFaced(card) && card.card_faces) {
|
||||||
|
return card.card_faces[faceIndex]?.image_uris?.normal || card.card_faces[faceIndex]?.image_uris?.small;
|
||||||
|
}
|
||||||
|
return card.image_uris?.normal || card.image_uris?.small || card.card_faces?.[0]?.image_uris?.normal;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to check if a card is in the collection
|
||||||
|
const isCardInCollection = (cardId: string, requiredQuantity: number = 1): boolean => {
|
||||||
|
const ownedQuantity = userCollection.get(cardId) || 0;
|
||||||
|
return ownedQuantity >= requiredQuantity;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to get missing cards
|
||||||
|
const getMissingCards = () => {
|
||||||
|
return selectedCards.filter(({ card, quantity }) => {
|
||||||
|
return !isCardInCollection(card.id, quantity);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add single card to collection
|
||||||
|
const handleAddCardToCollection = async (cardId: string, quantity: number) => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setAddingCardId(cardId);
|
||||||
|
await addCardToCollection(user.id, cardId, quantity);
|
||||||
|
|
||||||
|
// Update local collection state
|
||||||
|
setUserCollection(prev => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const currentQty = newMap.get(cardId) || 0;
|
||||||
|
newMap.set(cardId, currentQty + quantity);
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
|
||||||
|
setSnackbar({ message: 'Card added to collection!', type: 'success' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error adding card to collection:', error);
|
||||||
|
setSnackbar({ message: 'Failed to add card to collection', type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setAddingCardId(null);
|
||||||
|
setTimeout(() => setSnackbar(null), 3000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add all missing cards to collection
|
||||||
|
const handleAddAllMissingCards = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
const missingCards = getMissingCards();
|
||||||
|
if (missingCards.length === 0) {
|
||||||
|
setSnackbar({ message: 'All cards are already in your collection!', type: 'success' });
|
||||||
|
setTimeout(() => setSnackbar(null), 3000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsAddingAll(true);
|
||||||
|
|
||||||
|
const cardsToAdd = missingCards.map(({ card, quantity }) => {
|
||||||
|
const ownedQuantity = userCollection.get(card.id) || 0;
|
||||||
|
const neededQuantity = Math.max(0, quantity - ownedQuantity);
|
||||||
|
return {
|
||||||
|
cardId: card.id,
|
||||||
|
quantity: neededQuantity,
|
||||||
|
};
|
||||||
|
}).filter(c => c.quantity > 0);
|
||||||
|
|
||||||
|
await addMultipleCardsToCollection(user.id, cardsToAdd);
|
||||||
|
|
||||||
|
// Update local collection state
|
||||||
|
setUserCollection(prev => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
cardsToAdd.forEach(({ cardId, quantity }) => {
|
||||||
|
const currentQty = newMap.get(cardId) || 0;
|
||||||
|
newMap.set(cardId, currentQty + quantity);
|
||||||
|
});
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
|
||||||
|
setSnackbar({
|
||||||
|
message: `Successfully added ${cardsToAdd.length} card(s) to collection!`,
|
||||||
|
type: 'success'
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error adding cards to collection:', error);
|
||||||
|
setSnackbar({ message: 'Failed to add cards to collection', type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setIsAddingAll(false);
|
||||||
|
setTimeout(() => setSnackbar(null), 3000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleSearch = async (e: React.FormEvent) => {
|
const handleSearch = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!searchQuery.trim()) return;
|
if (!searchQuery.trim()) return;
|
||||||
@@ -162,12 +300,6 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
setSelectedCards(prev => {
|
setSelectedCards(prev => {
|
||||||
return prev.map(c => {
|
return prev.map(c => {
|
||||||
if (c.card.id === cardId) {
|
if (c.card.id === cardId) {
|
||||||
const isBasicLand =
|
|
||||||
c.card.name === 'Plains' ||
|
|
||||||
c.card.name === 'Island' ||
|
|
||||||
c.card.name === 'Swamp' ||
|
|
||||||
c.card.name === 'Mountain' ||
|
|
||||||
c.card.name === 'Forest';
|
|
||||||
return { ...c, quantity: quantity };
|
return { ...c, quantity: quantity };
|
||||||
}
|
}
|
||||||
return c;
|
return c;
|
||||||
@@ -180,8 +312,9 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
|
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
try {
|
try {
|
||||||
|
const deckId = currentDeckId || crypto.randomUUID();
|
||||||
const deckToSave: Deck = {
|
const deckToSave: Deck = {
|
||||||
id: initialDeck?.id || crypto.randomUUID(),
|
id: deckId,
|
||||||
name: deckName,
|
name: deckName,
|
||||||
format: deckFormat,
|
format: deckFormat,
|
||||||
cards: selectedCards,
|
cards: selectedCards,
|
||||||
@@ -190,8 +323,6 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const validation = validateDeck(deckToSave);
|
|
||||||
|
|
||||||
const deckData = {
|
const deckData = {
|
||||||
id: deckToSave.id,
|
id: deckToSave.id,
|
||||||
name: deckToSave.name,
|
name: deckToSave.name,
|
||||||
@@ -209,9 +340,14 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
|
|
||||||
if (deckError) throw deckError;
|
if (deckError) throw deckError;
|
||||||
|
|
||||||
|
// Update current deck ID if this was a new deck
|
||||||
|
if (!currentDeckId) {
|
||||||
|
setCurrentDeckId(deckId);
|
||||||
|
}
|
||||||
|
|
||||||
// Delete existing cards if updating
|
// Delete existing cards if updating
|
||||||
if (initialDeck) {
|
if (currentDeckId) {
|
||||||
await supabase.from('deck_cards').delete().eq('deck_id', initialDeck.id);
|
await supabase.from('deck_cards').delete().eq('deck_id', currentDeckId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save the deck cards
|
// Save the deck cards
|
||||||
@@ -328,11 +464,11 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
cardsToAdd.push({ card, quantity });
|
cardsToAdd.push({ card, quantity });
|
||||||
} else {
|
} else {
|
||||||
console.warn(`Card not found: ${cardName}`);
|
console.warn(`Card not found: ${cardName}`);
|
||||||
alert(`Card not found: ${cardName}`);
|
setSnackbar({ message: `Card not found: ${cardName}`, type: 'error' });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Failed to search card ${cardName}:`, error);
|
console.error(`Failed to search card ${cardName}:`, error);
|
||||||
alert(`Failed to search card ${cardName}: ${error}`);
|
setSnackbar({ message: `Failed to import card: ${cardName}`, type: 'error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,53 +498,151 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 text-white p-6">
|
<div className="bg-gray-900 text-white p-3 sm:p-6 pt-6 pb-20 md:pt-20 md:pb-6">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6">
|
||||||
{/* Card Search Section */}
|
{/* Card Search Section */}
|
||||||
<div className="lg:col-span-2 space-y-6">
|
<div className="lg:col-span-2 space-y-6">
|
||||||
<form onSubmit={handleSearch} className="flex gap-2">
|
{/* Mobile-First Search Bar */}
|
||||||
<div className="relative flex-1">
|
<form onSubmit={handleSearch} className="relative">
|
||||||
<Search
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
|
||||||
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
|
<input
|
||||||
size={20}
|
type="text"
|
||||||
/>
|
value={searchQuery}
|
||||||
<input
|
onChange={e => setSearchQuery(e.target.value)}
|
||||||
type="text"
|
className="w-full pl-10 pr-24 py-3 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 text-white"
|
||||||
value={searchQuery}
|
placeholder="Rechercher une carte..."
|
||||||
onChange={e => setSearchQuery(e.target.value)}
|
/>
|
||||||
className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-white"
|
{searchQuery && (
|
||||||
placeholder="Search for cards..."
|
<button
|
||||||
/>
|
type="button"
|
||||||
</div>
|
onClick={() => {
|
||||||
|
setSearchQuery('');
|
||||||
|
setSearchResults([]);
|
||||||
|
}}
|
||||||
|
className="absolute right-14 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white"
|
||||||
|
>
|
||||||
|
<XCircle size={20} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center gap-2"
|
className="absolute right-2 top-1/2 transform -translate-y-1/2 p-2 bg-blue-600 hover:bg-blue-700 rounded-md"
|
||||||
>
|
>
|
||||||
<Search size={20} />
|
<Search size={20} />
|
||||||
Search
|
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
|
{/* Vertical Card List for Mobile */}
|
||||||
{searchResults.map(card => (
|
<div className="space-y-2">
|
||||||
<div
|
{searchResults.map(card => {
|
||||||
key={card.id}
|
const currentFaceIndex = getCurrentFaceIndex(card.id);
|
||||||
className="bg-gray-800 rounded-lg overflow-hidden hover:ring-2 hover:ring-blue-500 transition-all"
|
const isMultiFaced = isDoubleFaced(card);
|
||||||
>
|
const inCollection = userCollection.get(card.id) || 0;
|
||||||
<MagicCard card={card} />
|
const isAddingThisCard = addingCardId === card.id;
|
||||||
<div className="p-4">
|
const cardInDeck = selectedCards.find(c => c.card.id === card.id);
|
||||||
<h3 className="font-bold mb-2">{card.name}</h3>
|
const quantityInDeck = cardInDeck?.quantity || 0;
|
||||||
|
|
||||||
|
const displayName = isMultiFaced && card.card_faces
|
||||||
|
? card.card_faces[currentFaceIndex]?.name || card.name
|
||||||
|
: card.name;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={card.id}
|
||||||
|
className="bg-gray-800 rounded-lg p-3 flex items-center gap-3 hover:bg-gray-750 transition-colors"
|
||||||
|
>
|
||||||
|
{/* Card Thumbnail */}
|
||||||
|
<div className="relative flex-shrink-0 w-16 h-22 rounded overflow-hidden">
|
||||||
|
{getCardImageUri(card, currentFaceIndex) ? (
|
||||||
|
<img
|
||||||
|
src={getCardImageUri(card, currentFaceIndex)}
|
||||||
|
alt={displayName}
|
||||||
|
className="w-full h-full object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="w-full h-full bg-gray-700" />
|
||||||
|
)}
|
||||||
|
{isMultiFaced && (
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggleCardFace(card.id, card.card_faces!.length);
|
||||||
|
}}
|
||||||
|
className="absolute bottom-0 right-0 bg-purple-600 text-white p-1 rounded-tl"
|
||||||
|
>
|
||||||
|
<RefreshCw size={10} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Card Info */}
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<h3 className="font-medium text-sm truncate">{displayName}</h3>
|
||||||
|
<div className="flex items-center gap-2 mt-1">
|
||||||
|
{card.mana_cost && (
|
||||||
|
<ManaCost cost={card.mana_cost} size={14} />
|
||||||
|
)}
|
||||||
|
{card.prices?.usd && (
|
||||||
|
<div className="text-xs text-gray-400">${card.prices.usd}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{inCollection > 0 && (
|
||||||
|
<div className="text-xs text-green-400 mt-1">
|
||||||
|
<CheckCircle size={12} className="inline mr-1" />
|
||||||
|
x{inCollection} in collection
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Add/Quantity Controls */}
|
||||||
|
{quantityInDeck > 0 ? (
|
||||||
|
<div className="flex-shrink-0 flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if (quantityInDeck === 1) {
|
||||||
|
removeCardFromDeck(card.id);
|
||||||
|
} else {
|
||||||
|
updateCardQuantity(card.id, quantityInDeck - 1);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-8 h-8 bg-red-600 hover:bg-red-700 rounded-full flex items-center justify-center transition-colors"
|
||||||
|
>
|
||||||
|
<Minus size={16} />
|
||||||
|
</button>
|
||||||
|
<span className="w-6 text-center text-sm font-medium">{quantityInDeck}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => addCardToDeck(card)}
|
||||||
|
className="w-8 h-8 bg-blue-600 hover:bg-blue-700 rounded-full flex items-center justify-center transition-colors"
|
||||||
|
>
|
||||||
|
<Plus size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => addCardToDeck(card)}
|
||||||
|
className="flex-shrink-0 w-10 h-10 bg-blue-600 hover:bg-blue-700 rounded-full flex items-center justify-center transition-colors"
|
||||||
|
>
|
||||||
|
<Plus size={20} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Add to Collection Button (hidden on mobile by default) */}
|
||||||
<button
|
<button
|
||||||
onClick={() => addCardToDeck(card)}
|
onClick={() => handleAddCardToCollection(card.id, 1)}
|
||||||
className="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center justify-center gap-2"
|
disabled={isAddingThisCard}
|
||||||
|
className="hidden sm:flex flex-shrink-0 w-10 h-10 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-full items-center justify-center transition-colors"
|
||||||
|
title="Add to collection"
|
||||||
>
|
>
|
||||||
<Plus size={20} />
|
{isAddingThisCard ? (
|
||||||
Add to Deck
|
<Loader2 className="animate-spin" size={20} />
|
||||||
|
) : (
|
||||||
|
<PackagePlus size={20} />
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
);
|
||||||
))}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -492,40 +726,45 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h3 className="font-bold text-xl mb-4">
|
<div className="flex items-center justify-between mb-4">
|
||||||
Cards ({selectedCards.reduce((acc, curr) => acc + curr.quantity, 0)})
|
<h3 className="font-bold text-xl">
|
||||||
</h3>
|
Cards ({selectedCards.reduce((acc, curr) => acc + curr.quantity, 0)})
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
{selectedCards.map(({ card, quantity }) => (
|
{selectedCards.map(({ card, quantity }) => (
|
||||||
<div
|
<div
|
||||||
key={card.id}
|
key={card.id}
|
||||||
className="flex items-center gap-4 bg-gray-700 p-2 rounded-lg"
|
className="flex items-center gap-3 p-2 rounded-lg bg-gray-700"
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
src={card.image_uris?.art_crop}
|
src={card.image_uris?.art_crop}
|
||||||
alt={card.name}
|
alt={card.name}
|
||||||
className="w-12 h-12 rounded"
|
className="w-10 h-10 rounded"
|
||||||
/>
|
/>
|
||||||
<div className="flex-1">
|
<div className="flex-1 min-w-0">
|
||||||
<h4 className="font-medium">{card.name}</h4>
|
<h4 className="font-medium text-sm truncate">{card.name}</h4>
|
||||||
{card.prices?.usd && (
|
{card.prices?.usd && (
|
||||||
<div className="text-sm text-gray-400">${card.prices.usd}</div>
|
<div className="text-xs text-gray-400">${card.prices.usd}</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<input
|
<div className="flex items-center gap-2">
|
||||||
type="number"
|
<input
|
||||||
value={quantity}
|
type="number"
|
||||||
onChange={e =>
|
value={quantity}
|
||||||
updateCardQuantity(card.id, parseInt(e.target.value))
|
onChange={e =>
|
||||||
}
|
updateCardQuantity(card.id, parseInt(e.target.value))
|
||||||
min="1"
|
}
|
||||||
className="w-16 px-2 py-1 bg-gray-600 border border-gray-500 rounded text-center"
|
min="1"
|
||||||
/>
|
className="w-14 px-2 py-1 bg-gray-600 border border-gray-500 rounded text-center text-sm"
|
||||||
<button
|
/>
|
||||||
onClick={() => removeCardFromDeck(card.id)}
|
<button
|
||||||
className="text-red-500 hover:text-red-400"
|
onClick={() => removeCardFromDeck(card.id)}
|
||||||
>
|
className="text-red-500 hover:text-red-400"
|
||||||
<Trash2 size={20} />
|
>
|
||||||
</button>
|
<Trash2 size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -555,25 +794,44 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<button
|
<div className="flex gap-2">
|
||||||
onClick={saveDeck}
|
{!isLoadingCollection && getMissingCards().length > 0 && (
|
||||||
disabled={
|
<button
|
||||||
!deckName.trim() || selectedCards.length === 0 || isSaving
|
onClick={handleAddAllMissingCards}
|
||||||
}
|
disabled={isAddingAll}
|
||||||
className="w-full px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg flex items-center justify-center gap-2 relative"
|
className="flex-1 px-4 py-2 bg-yellow-600 hover:bg-yellow-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg flex items-center justify-center gap-2"
|
||||||
>
|
title="Add missing cards to collection"
|
||||||
{isSaving ? (
|
>
|
||||||
<>
|
{isAddingAll ? (
|
||||||
<Loader2 className="animate-spin text-white absolute left-2 top-1/2 -translate-y-1/2" size={20} />
|
<Loader2 className="animate-spin" size={20} />
|
||||||
<span className="opacity-0">Save Deck</span>
|
) : (
|
||||||
</>
|
<>
|
||||||
) : (
|
<PackagePlus size={20} />
|
||||||
<>
|
<span className="hidden sm:inline">Add Missing</span>
|
||||||
<Save size={20} />
|
</>
|
||||||
<span>{initialDeck ? 'Update Deck' : 'Save Deck'}</span>
|
)}
|
||||||
</>
|
</button>
|
||||||
)}
|
)}
|
||||||
</button>
|
<button
|
||||||
|
onClick={saveDeck}
|
||||||
|
disabled={
|
||||||
|
!deckName.trim() || selectedCards.length === 0 || isSaving
|
||||||
|
}
|
||||||
|
className="flex-1 px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg flex items-center justify-center gap-2 relative"
|
||||||
|
>
|
||||||
|
{isSaving ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="animate-spin text-white absolute left-2 top-1/2 -translate-y-1/2" size={20} />
|
||||||
|
<span className="opacity-0">Save Deck</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Save size={20} />
|
||||||
|
<span>{initialDeck ? 'Update Deck' : 'Save Deck'}</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -601,4 +859,4 @@ export default function DeckManager({ initialDeck, onSave }: DeckManagerProps) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
312
src/components/Friends.tsx
Normal file
312
src/components/Friends.tsx
Normal file
@@ -0,0 +1,312 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Search, UserPlus, UserMinus, Check, X, Users, Clock, Send } from 'lucide-react';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import {
|
||||||
|
getFriends,
|
||||||
|
getPendingRequests,
|
||||||
|
getSentRequests,
|
||||||
|
searchUsers,
|
||||||
|
sendFriendRequest,
|
||||||
|
acceptFriendRequest,
|
||||||
|
declineFriendRequest,
|
||||||
|
removeFriend,
|
||||||
|
Friend,
|
||||||
|
} from '../services/friendsService';
|
||||||
|
|
||||||
|
type Tab = 'friends' | 'requests' | 'search';
|
||||||
|
|
||||||
|
export default function Friends() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [activeTab, setActiveTab] = useState<Tab>('friends');
|
||||||
|
const [friends, setFriends] = useState<Friend[]>([]);
|
||||||
|
const [pendingRequests, setPendingRequests] = useState<Friend[]>([]);
|
||||||
|
const [sentRequests, setSentRequests] = useState<Friend[]>([]);
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [searchResults, setSearchResults] = useState<{ id: string; username: string | null }[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [searching, setSearching] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
loadFriendsData();
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const loadFriendsData = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [friendsData, pendingData, sentData] = await Promise.all([
|
||||||
|
getFriends(user.id),
|
||||||
|
getPendingRequests(user.id),
|
||||||
|
getSentRequests(user.id),
|
||||||
|
]);
|
||||||
|
setFriends(friendsData);
|
||||||
|
setPendingRequests(pendingData);
|
||||||
|
setSentRequests(sentData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading friends:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSearch = async () => {
|
||||||
|
if (!user || searchQuery.trim().length < 2) return;
|
||||||
|
setSearching(true);
|
||||||
|
try {
|
||||||
|
const results = await searchUsers(searchQuery, user.id);
|
||||||
|
setSearchResults(results || []);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error searching users:', error);
|
||||||
|
} finally {
|
||||||
|
setSearching(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSendRequest = async (addresseeId: string) => {
|
||||||
|
if (!user) return;
|
||||||
|
try {
|
||||||
|
await sendFriendRequest(user.id, addresseeId);
|
||||||
|
setSearchResults((prev) => prev.filter((u) => u.id !== addresseeId));
|
||||||
|
await loadFriendsData();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error sending friend request:', error);
|
||||||
|
alert('Failed to send friend request');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAcceptRequest = async (friendshipId: string) => {
|
||||||
|
try {
|
||||||
|
await acceptFriendRequest(friendshipId);
|
||||||
|
await loadFriendsData();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error accepting request:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeclineRequest = async (friendshipId: string) => {
|
||||||
|
try {
|
||||||
|
await declineFriendRequest(friendshipId);
|
||||||
|
await loadFriendsData();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error declining request:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveFriend = async (friendshipId: string) => {
|
||||||
|
if (!confirm('Remove this friend?')) return;
|
||||||
|
try {
|
||||||
|
await removeFriend(friendshipId);
|
||||||
|
await loadFriendsData();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error removing friend:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isAlreadyFriendOrPending = (userId: string) => {
|
||||||
|
return (
|
||||||
|
friends.some((f) => f.id === userId) ||
|
||||||
|
pendingRequests.some((f) => f.id === userId) ||
|
||||||
|
sentRequests.some((f) => f.id === userId)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
|
||||||
|
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-900 text-white p-6">
|
||||||
|
<div className="max-w-2xl mx-auto">
|
||||||
|
<h1 className="text-3xl font-bold mb-6">Friends</h1>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex gap-2 mb-6">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('friends')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||||
|
activeTab === 'friends'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Users size={18} />
|
||||||
|
Friends ({friends.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('requests')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||||
|
activeTab === 'requests'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Clock size={18} />
|
||||||
|
Requests ({pendingRequests.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('search')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||||
|
activeTab === 'search'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Search size={18} />
|
||||||
|
Search
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Friends List */}
|
||||||
|
{activeTab === 'friends' && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{friends.length === 0 ? (
|
||||||
|
<p className="text-gray-400 text-center py-8">
|
||||||
|
No friends yet. Search for users to add them!
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
friends.map((friend) => (
|
||||||
|
<div
|
||||||
|
key={friend.id}
|
||||||
|
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
|
||||||
|
>
|
||||||
|
<span className="font-medium">{friend.username || 'Unknown'}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => handleRemoveFriend(friend.friendshipId)}
|
||||||
|
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition"
|
||||||
|
title="Remove friend"
|
||||||
|
>
|
||||||
|
<UserMinus size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Requests Tab */}
|
||||||
|
{activeTab === 'requests' && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Received Requests */}
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold mb-3 text-gray-300">Received Requests</h2>
|
||||||
|
{pendingRequests.length === 0 ? (
|
||||||
|
<p className="text-gray-500 text-sm">No pending requests</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{pendingRequests.map((request) => (
|
||||||
|
<div
|
||||||
|
key={request.id}
|
||||||
|
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
|
||||||
|
>
|
||||||
|
<span className="font-medium">{request.username || 'Unknown'}</span>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => handleAcceptRequest(request.friendshipId)}
|
||||||
|
className="p-2 text-green-400 hover:bg-green-400/20 rounded-lg transition"
|
||||||
|
title="Accept"
|
||||||
|
>
|
||||||
|
<Check size={20} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeclineRequest(request.friendshipId)}
|
||||||
|
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition"
|
||||||
|
title="Decline"
|
||||||
|
>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sent Requests */}
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold mb-3 text-gray-300">Sent Requests</h2>
|
||||||
|
{sentRequests.length === 0 ? (
|
||||||
|
<p className="text-gray-500 text-sm">No sent requests</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{sentRequests.map((request) => (
|
||||||
|
<div
|
||||||
|
key={request.id}
|
||||||
|
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Send size={16} className="text-gray-500" />
|
||||||
|
<span className="font-medium">{request.username || 'Unknown'}</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-sm text-yellow-500">Pending</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Search Tab */}
|
||||||
|
{activeTab === 'search' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
|
||||||
|
placeholder="Search by username..."
|
||||||
|
className="flex-1 px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleSearch}
|
||||||
|
disabled={searching || searchQuery.trim().length < 2}
|
||||||
|
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg transition"
|
||||||
|
>
|
||||||
|
{searching ? (
|
||||||
|
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
|
||||||
|
) : (
|
||||||
|
<Search size={20} />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{searchResults.length > 0 && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{searchResults.map((result) => (
|
||||||
|
<div
|
||||||
|
key={result.id}
|
||||||
|
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
|
||||||
|
>
|
||||||
|
<span className="font-medium">{result.username || 'Unknown'}</span>
|
||||||
|
{isAlreadyFriendOrPending(result.id) ? (
|
||||||
|
<span className="text-sm text-gray-500">Already connected</span>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => handleSendRequest(result.id)}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition text-sm"
|
||||||
|
>
|
||||||
|
<UserPlus size={16} />
|
||||||
|
Add Friend
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{searchQuery.length >= 2 && searchResults.length === 0 && !searching && (
|
||||||
|
<p className="text-gray-400 text-center py-4">No users found</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,11 +6,14 @@ interface MagicCardProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const MagicCard = ({ card }: MagicCardProps) => {
|
const MagicCard = ({ card }: MagicCardProps) => {
|
||||||
|
// Handle both regular cards and double-faced cards (transform, modal_dfc, etc)
|
||||||
|
const imageUri = card.image_uris?.normal || card.card_faces?.[0]?.image_uris?.normal;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative card-hover animate-fade-in">
|
<div className="relative card-hover animate-fade-in">
|
||||||
{card.image_uris?.normal ? (
|
{imageUri ? (
|
||||||
<img
|
<img
|
||||||
src={card.image_uris.normal}
|
src={imageUri}
|
||||||
alt={card.name}
|
alt={card.name}
|
||||||
className="w-full h-auto rounded-lg transition-smooth"
|
className="w-full h-auto rounded-lg transition-smooth"
|
||||||
/>
|
/>
|
||||||
|
|||||||
71
src/components/ManaCost.tsx
Normal file
71
src/components/ManaCost.tsx
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
// Map mana symbols to their icon paths
|
||||||
|
const MANA_ICONS: Record<string, string> = {
|
||||||
|
W: '/mana-color/plains.png',
|
||||||
|
U: '/mana-color/island.png',
|
||||||
|
B: '/mana-color/swamp.png',
|
||||||
|
R: '/mana-color/moutain.png', // Note: filename has typo "moutain"
|
||||||
|
G: '/mana-color/forest.png',
|
||||||
|
};
|
||||||
|
|
||||||
|
interface ManaSymbolProps {
|
||||||
|
symbol: string;
|
||||||
|
size?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Renders a single mana symbol (either as an icon or as text for numbers/other)
|
||||||
|
export function ManaSymbol({ symbol, size = 16 }: ManaSymbolProps) {
|
||||||
|
const iconPath = MANA_ICONS[symbol];
|
||||||
|
|
||||||
|
if (iconPath) {
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
src={iconPath}
|
||||||
|
alt={symbol}
|
||||||
|
className="inline-block"
|
||||||
|
style={{ width: size, height: size }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// For numbers and other symbols, show as a circle with the symbol
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center justify-center bg-gray-500 text-white font-bold rounded-full"
|
||||||
|
style={{ width: size, height: size, fontSize: size * 0.6 }}
|
||||||
|
>
|
||||||
|
{symbol}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ManaCostProps {
|
||||||
|
cost: string;
|
||||||
|
size?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parses and renders a full mana cost string like "{2}{W}{U}"
|
||||||
|
export function ManaCost({ cost, size = 16 }: ManaCostProps) {
|
||||||
|
if (!cost) return null;
|
||||||
|
|
||||||
|
// Parse mana cost string: {2}{W}{U} -> ['2', 'W', 'U']
|
||||||
|
const symbols = cost.match(/\{([^}]+)\}/g)?.map(s => s.slice(1, -1)) || [];
|
||||||
|
|
||||||
|
if (symbols.length === 0) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-0.5">
|
||||||
|
{symbols.map((symbol, index) => (
|
||||||
|
<ManaSymbol key={index} symbol={symbol} size={size} />
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to get icon path for a color (for use in filters, etc.)
|
||||||
|
export function getManaIconPath(color: string): string | null {
|
||||||
|
return MANA_ICONS[color] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ManaCost;
|
||||||
80
src/components/Modal.tsx
Normal file
80
src/components/Modal.tsx
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import React, { useEffect } from 'react';
|
||||||
|
import { X } from 'lucide-react';
|
||||||
|
|
||||||
|
interface ModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
children: React.ReactNode;
|
||||||
|
size?: 'sm' | 'md' | 'lg';
|
||||||
|
showCloseButton?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Modal({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
children,
|
||||||
|
size = 'md',
|
||||||
|
showCloseButton = true
|
||||||
|
}: ModalProps) {
|
||||||
|
// Close modal on ESC key
|
||||||
|
useEffect(() => {
|
||||||
|
const handleEscape = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape' && isOpen) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('keydown', handleEscape);
|
||||||
|
return () => document.removeEventListener('keydown', handleEscape);
|
||||||
|
}, [isOpen, onClose]);
|
||||||
|
|
||||||
|
// Prevent body scroll when modal is open
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen) {
|
||||||
|
document.body.style.overflow = 'hidden';
|
||||||
|
} else {
|
||||||
|
document.body.style.overflow = 'unset';
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = 'unset';
|
||||||
|
};
|
||||||
|
}, [isOpen]);
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const sizeClasses = {
|
||||||
|
sm: 'max-w-md',
|
||||||
|
md: 'max-w-lg',
|
||||||
|
lg: 'max-w-2xl',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Backdrop */}
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-black bg-opacity-50 z-50 transition-opacity duration-300 animate-fade-in"
|
||||||
|
onClick={onClose}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Modal */}
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none">
|
||||||
|
<div
|
||||||
|
className={`${sizeClasses[size]} w-full bg-gray-800 rounded-lg shadow-2xl pointer-events-auto animate-scale-in`}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{showCloseButton && (
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors z-10"
|
||||||
|
>
|
||||||
|
<X size={24} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import React, { useState, useRef, useEffect } from 'react';
|
import React, { useState, useRef, useEffect } from 'react';
|
||||||
import { Home, PlusSquare, Library, LogOut, Settings, ChevronDown, Search, Heart, Menu } from 'lucide-react';
|
import { Home, PlusSquare, Library, LogOut, Settings, ChevronDown, Search, Heart, Menu, Users, ArrowLeftRight, Globe } from 'lucide-react';
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import { supabase } from '../lib/supabase';
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'profile' | 'search' | 'life-counter';
|
type Page = 'home' | 'deck' | 'login' | 'collection' | 'profile' | 'search' | 'life-counter' | 'friends' | 'trades' | 'community';
|
||||||
|
|
||||||
interface NavigationProps {
|
interface NavigationProps {
|
||||||
currentPage: Page;
|
currentPage: Page;
|
||||||
@@ -51,11 +51,13 @@ import React, { useState, useRef, useEffect } from 'react';
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{ id: 'home' as const, label: 'Home', icon: Home },
|
{ id: 'home' as const, label: 'Decks', icon: Library },
|
||||||
{ id: 'deck' as const, label: 'New Deck', icon: PlusSquare },
|
|
||||||
{ id: 'collection' as const, label: 'Collection', icon: Library },
|
{ id: 'collection' as const, label: 'Collection', icon: Library },
|
||||||
|
{ id: 'community' as const, label: 'Community', icon: Globe },
|
||||||
|
{ id: 'friends' as const, label: 'Friends', icon: Users },
|
||||||
|
{ id: 'trades' as const, label: 'Trades', icon: ArrowLeftRight },
|
||||||
{ id: 'search' as const, label: 'Search', icon: Search },
|
{ id: 'search' as const, label: 'Search', icon: Search },
|
||||||
{ id: 'life-counter' as const, label: 'Life Counter', icon: Heart },
|
{ id: 'life-counter' as const, label: 'Life', icon: Heart },
|
||||||
];
|
];
|
||||||
|
|
||||||
const handleSignOut = async () => {
|
const handleSignOut = async () => {
|
||||||
@@ -140,60 +142,64 @@ import React, { useState, useRef, useEffect } from 'react';
|
|||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* Mobile Navigation - Bottom */}
|
{/* Mobile Navigation - Bottom */}
|
||||||
<nav className="md:hidden fixed bottom-0 left-0 right-0 bg-gray-800 border-t border-gray-700 z-50 animate-slide-in-right">
|
<nav className="md:hidden fixed bottom-0 left-0 right-0 bg-gray-800 border-t border-gray-700 z-50 safe-area-bottom">
|
||||||
<div className="flex justify-between items-center h-16 px-4">
|
<div className="flex justify-around items-center h-16 px-2">
|
||||||
<span className="text-2xl font-bold text-orange-500 animate-bounce-in">Deckerr</span>
|
{navItems.map((item) => (
|
||||||
<div className="relative" ref={mobileMenuRef}>
|
<button
|
||||||
|
key={item.id}
|
||||||
|
onClick={() => setCurrentPage(item.id)}
|
||||||
|
className={`flex flex-col items-center justify-center flex-1 h-full transition-colors ${
|
||||||
|
currentPage === item.id
|
||||||
|
? 'text-blue-500'
|
||||||
|
: 'text-gray-400 hover:text-gray-200'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<item.icon size={20} />
|
||||||
|
<span className="text-xs mt-1">{item.label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Settings with dropdown */}
|
||||||
|
<div className="relative flex-1 h-full" ref={mobileMenuRef}>
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowMobileMenu(!showMobileMenu)}
|
onClick={() => setShowMobileMenu(!showMobileMenu)}
|
||||||
className="text-gray-300 hover:text-white"
|
className={`flex flex-col items-center justify-center w-full h-full transition-colors ${
|
||||||
|
currentPage === 'profile' || showMobileMenu
|
||||||
|
? 'text-blue-500'
|
||||||
|
: 'text-gray-400 hover:text-gray-200'
|
||||||
|
}`}
|
||||||
>
|
>
|
||||||
<Menu size={24} />
|
<Settings size={20} />
|
||||||
|
<span className="text-xs mt-1">Settings</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{showMobileMenu && (
|
{showMobileMenu && (
|
||||||
<div className="absolute right-0 bottom-16 w-48 bg-gray-800 rounded-md shadow-lg py-1 border border-gray-700 animate-scale-in glass-effect">
|
<div className="absolute right-0 bottom-full mb-2 w-48 bg-gray-800 rounded-lg shadow-xl py-1 border border-gray-700 animate-scale-in">
|
||||||
{navItems.map((item) => (
|
<button
|
||||||
<button
|
onClick={() => {
|
||||||
key={item.id}
|
setCurrentPage('profile');
|
||||||
onClick={() => {
|
setShowMobileMenu(false);
|
||||||
setCurrentPage(item.id);
|
}}
|
||||||
setShowMobileMenu(false);
|
className="flex items-center space-x-3 w-full px-4 py-3 text-sm text-gray-300 hover:bg-gray-700 transition-colors"
|
||||||
}}
|
>
|
||||||
className="flex items-center space-x-2 w-full px-4 py-2 text-sm text-gray-300 hover:bg-gray-700 transition-smooth"
|
<Settings size={18} />
|
||||||
>
|
<span>Profile</span>
|
||||||
<item.icon size={16} />
|
</button>
|
||||||
<span>{item.label}</span>
|
<button
|
||||||
</button>
|
onClick={() => {
|
||||||
))}
|
handleSignOut();
|
||||||
{user && (
|
setShowMobileMenu(false);
|
||||||
<>
|
}}
|
||||||
<button
|
className="flex items-center space-x-3 w-full px-4 py-3 text-sm text-red-400 hover:bg-gray-700 transition-colors"
|
||||||
onClick={() => {
|
>
|
||||||
setCurrentPage('profile');
|
<LogOut size={18} />
|
||||||
setShowMobileMenu(false);
|
<span>Sign Out</span>
|
||||||
}}
|
</button>
|
||||||
className="flex items-center space-x-2 w-full px-4 py-2 text-sm text-gray-300 hover:bg-gray-700 transition-smooth"
|
|
||||||
>
|
|
||||||
<Settings size={16} />
|
|
||||||
<span>Profile Settings</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={handleSignOut}
|
|
||||||
className="flex items-center space-x-2 w-full px-4 py-2 text-sm text-gray-300 hover:bg-gray-700 transition-smooth"
|
|
||||||
>
|
|
||||||
<LogOut size={16} />
|
|
||||||
<span>Sign Out</span>
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* Content Padding */}
|
|
||||||
<div className="md:pt-16 pb-16 md:pb-0" />
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
128
src/components/PWAInstallPrompt.tsx
Normal file
128
src/components/PWAInstallPrompt.tsx
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Download, X } from 'lucide-react';
|
||||||
|
|
||||||
|
interface BeforeInstallPromptEvent extends Event {
|
||||||
|
prompt: () => Promise<void>;
|
||||||
|
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PWAInstallPrompt() {
|
||||||
|
const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null);
|
||||||
|
const [showPrompt, setShowPrompt] = useState(false);
|
||||||
|
const [isInstalled, setIsInstalled] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Check if already installed
|
||||||
|
const isStandalone = window.matchMedia('(display-mode: standalone)').matches;
|
||||||
|
if (isStandalone || (window.navigator as any).standalone) {
|
||||||
|
setIsInstalled(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user dismissed the prompt before
|
||||||
|
const dismissed = localStorage.getItem('pwa-install-dismissed');
|
||||||
|
const dismissedTime = dismissed ? parseInt(dismissed) : 0;
|
||||||
|
const daysSinceDismissed = (Date.now() - dismissedTime) / (1000 * 60 * 60 * 24);
|
||||||
|
|
||||||
|
// Show prompt again after 7 days
|
||||||
|
if (daysSinceDismissed > 7) {
|
||||||
|
localStorage.removeItem('pwa-install-dismissed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const handler = (e: Event) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const promptEvent = e as BeforeInstallPromptEvent;
|
||||||
|
setDeferredPrompt(promptEvent);
|
||||||
|
|
||||||
|
// Show prompt if not dismissed recently
|
||||||
|
if (!dismissed || daysSinceDismissed > 7) {
|
||||||
|
setShowPrompt(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('beforeinstallprompt', handler);
|
||||||
|
|
||||||
|
// Detect if app was installed
|
||||||
|
window.addEventListener('appinstalled', () => {
|
||||||
|
setIsInstalled(true);
|
||||||
|
setShowPrompt(false);
|
||||||
|
setDeferredPrompt(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('beforeinstallprompt', handler);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleInstallClick = async () => {
|
||||||
|
if (!deferredPrompt) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await deferredPrompt.prompt();
|
||||||
|
const choiceResult = await deferredPrompt.userChoice;
|
||||||
|
|
||||||
|
if (choiceResult.outcome === 'accepted') {
|
||||||
|
console.log('User accepted the install prompt');
|
||||||
|
setShowPrompt(false);
|
||||||
|
} else {
|
||||||
|
console.log('User dismissed the install prompt');
|
||||||
|
handleDismiss();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error during installation:', error);
|
||||||
|
} finally {
|
||||||
|
setDeferredPrompt(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDismiss = () => {
|
||||||
|
setShowPrompt(false);
|
||||||
|
localStorage.setItem('pwa-install-dismissed', Date.now().toString());
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isInstalled || !showPrompt) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed bottom-20 md:bottom-4 left-4 right-4 md:left-auto md:right-4 md:max-w-sm z-50 animate-slide-in-bottom">
|
||||||
|
<div className="bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg shadow-2xl p-4 text-white">
|
||||||
|
<button
|
||||||
|
onClick={handleDismiss}
|
||||||
|
className="absolute top-2 right-2 text-white/80 hover:text-white transition-colors"
|
||||||
|
aria-label="Dismiss"
|
||||||
|
>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-start gap-3 pr-6">
|
||||||
|
<div className="bg-white/20 rounded-lg p-2 flex-shrink-0">
|
||||||
|
<Download size={24} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1">
|
||||||
|
<h3 className="font-bold text-lg mb-1">Install Deckerr</h3>
|
||||||
|
<p className="text-sm text-white/90 mb-3">
|
||||||
|
Install our app for quick access and offline support!
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={handleInstallClick}
|
||||||
|
className="flex-1 bg-white text-blue-600 font-semibold py-2 px-4 rounded-lg hover:bg-blue-50 transition-colors min-h-[44px]"
|
||||||
|
>
|
||||||
|
Install
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleDismiss}
|
||||||
|
className="flex-1 bg-white/20 font-semibold py-2 px-4 rounded-lg hover:bg-white/30 transition-colors min-h-[44px]"
|
||||||
|
>
|
||||||
|
Not Now
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,14 +1,23 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Save } from 'lucide-react';
|
import { Save, Globe, Users, Lock } from 'lucide-react';
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import { supabase } from '../lib/supabase';
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
const THEME_COLORS = ['red', 'green', 'blue', 'yellow', 'grey', 'purple'];
|
const THEME_COLORS = ['red', 'green', 'blue', 'yellow', 'grey', 'purple'];
|
||||||
|
|
||||||
|
const VISIBILITY_OPTIONS = [
|
||||||
|
{ value: 'public', label: 'Public', icon: Globe, description: 'Anyone can view your collection' },
|
||||||
|
{ value: 'friends', label: 'Friends Only', icon: Users, description: 'Only friends can view your collection' },
|
||||||
|
{ value: 'private', label: 'Private', icon: Lock, description: 'Only you can view your collection' },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
type CollectionVisibility = 'public' | 'friends' | 'private';
|
||||||
|
|
||||||
export default function Profile() {
|
export default function Profile() {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [username, setUsername] = useState('');
|
const [username, setUsername] = useState('');
|
||||||
const [themeColor, setThemeColor] = useState('blue');
|
const [themeColor, setThemeColor] = useState('blue');
|
||||||
|
const [collectionVisibility, setCollectionVisibility] = useState<CollectionVisibility>('private');
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
@@ -17,13 +26,14 @@ export default function Profile() {
|
|||||||
if (user) {
|
if (user) {
|
||||||
const { data, error } = await supabase
|
const { data, error } = await supabase
|
||||||
.from('profiles')
|
.from('profiles')
|
||||||
.select('username, theme_color')
|
.select('username, theme_color, collection_visibility')
|
||||||
.eq('id', user.id)
|
.eq('id', user.id)
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (data) {
|
if (data) {
|
||||||
setUsername(data.username || '');
|
setUsername(data.username || '');
|
||||||
setThemeColor(data.theme_color || 'blue');
|
setThemeColor(data.theme_color || 'blue');
|
||||||
|
setCollectionVisibility((data.collection_visibility as CollectionVisibility) || 'private');
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -44,6 +54,7 @@ export default function Profile() {
|
|||||||
id: user.id,
|
id: user.id,
|
||||||
username,
|
username,
|
||||||
theme_color: themeColor,
|
theme_color: themeColor,
|
||||||
|
collection_visibility: collectionVisibility,
|
||||||
updated_at: new Date()
|
updated_at: new Date()
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -88,13 +99,13 @@ export default function Profile() {
|
|||||||
<label className="block text-sm font-medium text-gray-300 mb-2">
|
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||||
Theme Color
|
Theme Color
|
||||||
</label>
|
</label>
|
||||||
<div className="grid grid-cols-3 gap-4">
|
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 sm:gap-4">
|
||||||
{THEME_COLORS.map((color) => (
|
{THEME_COLORS.map((color) => (
|
||||||
<button
|
<button
|
||||||
key={color}
|
key={color}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setThemeColor(color)}
|
onClick={() => setThemeColor(color)}
|
||||||
className={`h-12 rounded-lg border-2 transition-all capitalize
|
className={`h-12 sm:h-14 rounded-lg border-2 transition-all capitalize text-sm sm:text-base
|
||||||
${themeColor === color
|
${themeColor === color
|
||||||
? 'border-white scale-105'
|
? 'border-white scale-105'
|
||||||
: 'border-transparent hover:border-gray-600'
|
: 'border-transparent hover:border-gray-600'
|
||||||
@@ -107,10 +118,39 @@ export default function Profile() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||||
|
Collection Visibility
|
||||||
|
</label>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{VISIBILITY_OPTIONS.map((option) => {
|
||||||
|
const Icon = option.icon;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={option.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCollectionVisibility(option.value)}
|
||||||
|
className={`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left
|
||||||
|
${collectionVisibility === option.value
|
||||||
|
? 'border-blue-500 bg-blue-500/10'
|
||||||
|
: 'border-gray-700 hover:border-gray-600 bg-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Icon size={20} className={collectionVisibility === option.value ? 'text-blue-400' : 'text-gray-400'} />
|
||||||
|
<div>
|
||||||
|
<div className="font-medium">{option.label}</div>
|
||||||
|
<div className="text-sm text-gray-400">{option.description}</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={saving}
|
disabled={saving}
|
||||||
className="w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-semibold py-2 px-4 rounded-lg transition duration-200"
|
className="w-full min-h-[44px] flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-semibold py-3 px-4 rounded-lg transition duration-200"
|
||||||
>
|
>
|
||||||
{saving ? (
|
{saving ? (
|
||||||
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
|
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
|
||||||
@@ -125,4 +165,4 @@ export default function Profile() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
380
src/components/TradeCreator.tsx
Normal file
380
src/components/TradeCreator.tsx
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { X, ArrowLeftRight, Plus, Minus, Send, Gift } from 'lucide-react';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||||
|
import { createTrade } from '../services/tradesService';
|
||||||
|
import { Card } from '../types';
|
||||||
|
|
||||||
|
interface CollectionItem {
|
||||||
|
card: Card;
|
||||||
|
quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TradeCreatorProps {
|
||||||
|
receiverId: string;
|
||||||
|
receiverUsername: string;
|
||||||
|
receiverCollection: CollectionItem[];
|
||||||
|
onClose: () => void;
|
||||||
|
onTradeCreated: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SelectedCard {
|
||||||
|
card: Card;
|
||||||
|
quantity: number;
|
||||||
|
maxQuantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TradeCreator({
|
||||||
|
receiverId,
|
||||||
|
receiverUsername,
|
||||||
|
receiverCollection,
|
||||||
|
onClose,
|
||||||
|
onTradeCreated,
|
||||||
|
}: TradeCreatorProps) {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [myCollection, setMyCollection] = useState<CollectionItem[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [message, setMessage] = useState('');
|
||||||
|
|
||||||
|
// Cards I'm offering (from my collection)
|
||||||
|
const [myOfferedCards, setMyOfferedCards] = useState<Map<string, SelectedCard>>(new Map());
|
||||||
|
// Cards I want (from their collection)
|
||||||
|
const [wantedCards, setWantedCards] = useState<Map<string, SelectedCard>>(new Map());
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadMyCollection();
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const loadMyCollection = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const collectionMap = await getUserCollection(user.id);
|
||||||
|
if (collectionMap.size === 0) {
|
||||||
|
setMyCollection([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cardIds = Array.from(collectionMap.keys());
|
||||||
|
const cards = await getCardsByIds(cardIds);
|
||||||
|
|
||||||
|
const collectionWithCards = cards.map((card) => ({
|
||||||
|
card,
|
||||||
|
quantity: collectionMap.get(card.id) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
setMyCollection(collectionWithCards);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading my collection:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const addToOffer = (card: Card, maxQuantity: number) => {
|
||||||
|
setMyOfferedCards((prev) => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const existing = newMap.get(card.id);
|
||||||
|
if (existing) {
|
||||||
|
if (existing.quantity < existing.maxQuantity) {
|
||||||
|
newMap.set(card.id, { ...existing, quantity: existing.quantity + 1 });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
newMap.set(card.id, { card, quantity: 1, maxQuantity });
|
||||||
|
}
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeFromOffer = (cardId: string) => {
|
||||||
|
setMyOfferedCards((prev) => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const existing = newMap.get(cardId);
|
||||||
|
if (existing && existing.quantity > 1) {
|
||||||
|
newMap.set(cardId, { ...existing, quantity: existing.quantity - 1 });
|
||||||
|
} else {
|
||||||
|
newMap.delete(cardId);
|
||||||
|
}
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const addToWanted = (card: Card, maxQuantity: number) => {
|
||||||
|
setWantedCards((prev) => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const existing = newMap.get(card.id);
|
||||||
|
if (existing) {
|
||||||
|
if (existing.quantity < existing.maxQuantity) {
|
||||||
|
newMap.set(card.id, { ...existing, quantity: existing.quantity + 1 });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
newMap.set(card.id, { card, quantity: 1, maxQuantity });
|
||||||
|
}
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeFromWanted = (cardId: string) => {
|
||||||
|
setWantedCards((prev) => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const existing = newMap.get(cardId);
|
||||||
|
if (existing && existing.quantity > 1) {
|
||||||
|
newMap.set(cardId, { ...existing, quantity: existing.quantity - 1 });
|
||||||
|
} else {
|
||||||
|
newMap.delete(cardId);
|
||||||
|
}
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
// At least one side should have cards (allowing gifts)
|
||||||
|
if (myOfferedCards.size === 0 && wantedCards.size === 0) {
|
||||||
|
alert('Please select at least one card to trade or gift');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
const senderCards = Array.from(myOfferedCards.values()).map((item) => ({
|
||||||
|
cardId: item.card.id,
|
||||||
|
quantity: item.quantity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const receiverCards = Array.from(wantedCards.values()).map((item) => ({
|
||||||
|
cardId: item.card.id,
|
||||||
|
quantity: item.quantity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await createTrade({
|
||||||
|
senderId: user.id,
|
||||||
|
receiverId,
|
||||||
|
message: message || undefined,
|
||||||
|
senderCards,
|
||||||
|
receiverCards,
|
||||||
|
});
|
||||||
|
|
||||||
|
onTradeCreated();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating trade:', error);
|
||||||
|
alert('Failed to create trade');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isGift = myOfferedCards.size > 0 && wantedCards.size === 0;
|
||||||
|
const isRequest = myOfferedCards.size === 0 && wantedCards.size > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center p-4">
|
||||||
|
<div className="bg-gray-800 rounded-lg w-full max-w-6xl max-h-[90vh] overflow-hidden flex flex-col">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between p-4 border-b border-gray-700">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ArrowLeftRight size={24} className="text-blue-400" />
|
||||||
|
<h2 className="text-xl font-bold">Trade with {receiverUsername}</h2>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="p-2 hover:bg-gray-700 rounded-lg transition"
|
||||||
|
>
|
||||||
|
<X size={24} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 overflow-hidden flex flex-col md:flex-row">
|
||||||
|
{/* My Collection (Left) */}
|
||||||
|
<div className="flex-1 p-4 border-b md:border-b-0 md:border-r border-gray-700 overflow-y-auto">
|
||||||
|
<h3 className="text-lg font-semibold mb-3 text-green-400">
|
||||||
|
My Collection (I give)
|
||||||
|
</h3>
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
|
||||||
|
</div>
|
||||||
|
) : myCollection.length === 0 ? (
|
||||||
|
<p className="text-gray-400 text-center py-4">Your collection is empty</p>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||||
|
{myCollection.map(({ card, quantity }) => {
|
||||||
|
const offered = myOfferedCards.get(card.id);
|
||||||
|
const remainingQty = quantity - (offered?.quantity || 0);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={card.id}
|
||||||
|
className={`relative cursor-pointer rounded-lg overflow-hidden transition ${
|
||||||
|
offered ? 'ring-2 ring-green-500' : 'hover:ring-2 hover:ring-gray-500'
|
||||||
|
}`}
|
||||||
|
onClick={() => remainingQty > 0 && addToOffer(card, quantity)}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={card.image_uris?.small}
|
||||||
|
alt={card.name}
|
||||||
|
className={`w-full h-auto ${remainingQty === 0 ? 'opacity-50' : ''}`}
|
||||||
|
/>
|
||||||
|
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded">
|
||||||
|
{remainingQty}/{quantity}
|
||||||
|
</div>
|
||||||
|
{offered && (
|
||||||
|
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-xs px-1.5 py-0.5 rounded">
|
||||||
|
+{offered.quantity}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Their Collection (Right) */}
|
||||||
|
<div className="flex-1 p-4 overflow-y-auto">
|
||||||
|
<h3 className="text-lg font-semibold mb-3 text-blue-400">
|
||||||
|
{receiverUsername}'s Collection (I want)
|
||||||
|
</h3>
|
||||||
|
{receiverCollection.length === 0 ? (
|
||||||
|
<p className="text-gray-400 text-center py-4">Their collection is empty</p>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||||
|
{receiverCollection.map(({ card, quantity }) => {
|
||||||
|
const wanted = wantedCards.get(card.id);
|
||||||
|
const remainingQty = quantity - (wanted?.quantity || 0);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={card.id}
|
||||||
|
className={`relative cursor-pointer rounded-lg overflow-hidden transition ${
|
||||||
|
wanted ? 'ring-2 ring-blue-500' : 'hover:ring-2 hover:ring-gray-500'
|
||||||
|
}`}
|
||||||
|
onClick={() => remainingQty > 0 && addToWanted(card, quantity)}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={card.image_uris?.small}
|
||||||
|
alt={card.name}
|
||||||
|
className={`w-full h-auto ${remainingQty === 0 ? 'opacity-50' : ''}`}
|
||||||
|
/>
|
||||||
|
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded">
|
||||||
|
{remainingQty}/{quantity}
|
||||||
|
</div>
|
||||||
|
{wanted && (
|
||||||
|
<div className="absolute bottom-1 left-1 bg-blue-500 text-white text-xs px-1.5 py-0.5 rounded">
|
||||||
|
+{wanted.quantity}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Trade Summary */}
|
||||||
|
<div className="border-t border-gray-700 p-4">
|
||||||
|
<div className="flex flex-col md:flex-row gap-4 mb-4">
|
||||||
|
{/* I Give */}
|
||||||
|
<div className="flex-1">
|
||||||
|
<h4 className="text-sm font-semibold text-green-400 mb-2">I Give:</h4>
|
||||||
|
{myOfferedCards.size === 0 ? (
|
||||||
|
<p className="text-gray-500 text-sm">Nothing selected (gift request)</p>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{Array.from(myOfferedCards.values()).map((item) => (
|
||||||
|
<div
|
||||||
|
key={item.card.id}
|
||||||
|
className="flex items-center gap-1 bg-green-900/50 px-2 py-1 rounded text-sm"
|
||||||
|
>
|
||||||
|
<span>{item.card.name}</span>
|
||||||
|
<span className="text-green-400">x{item.quantity}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => removeFromOffer(item.card.id)}
|
||||||
|
className="ml-1 text-red-400 hover:text-red-300"
|
||||||
|
>
|
||||||
|
<Minus size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* I Want */}
|
||||||
|
<div className="flex-1">
|
||||||
|
<h4 className="text-sm font-semibold text-blue-400 mb-2">I Want:</h4>
|
||||||
|
{wantedCards.size === 0 ? (
|
||||||
|
<p className="text-gray-500 text-sm">Nothing selected (gift)</p>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{Array.from(wantedCards.values()).map((item) => (
|
||||||
|
<div
|
||||||
|
key={item.card.id}
|
||||||
|
className="flex items-center gap-1 bg-blue-900/50 px-2 py-1 rounded text-sm"
|
||||||
|
>
|
||||||
|
<span>{item.card.name}</span>
|
||||||
|
<span className="text-blue-400">x{item.quantity}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => removeFromWanted(item.card.id)}
|
||||||
|
className="ml-1 text-red-400 hover:text-red-300"
|
||||||
|
>
|
||||||
|
<Minus size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Message */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={message}
|
||||||
|
onChange={(e) => setMessage(e.target.value)}
|
||||||
|
placeholder="Add a message (optional)"
|
||||||
|
className="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Submit */}
|
||||||
|
<div className="flex justify-end gap-3">
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={submitting || (myOfferedCards.size === 0 && wantedCards.size === 0)}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg transition"
|
||||||
|
>
|
||||||
|
{submitting ? (
|
||||||
|
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
|
||||||
|
) : isGift ? (
|
||||||
|
<>
|
||||||
|
<Gift size={20} />
|
||||||
|
Send Gift
|
||||||
|
</>
|
||||||
|
) : isRequest ? (
|
||||||
|
<>
|
||||||
|
<Send size={20} />
|
||||||
|
Request Cards
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Send size={20} />
|
||||||
|
Propose Trade
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
326
src/components/Trades.tsx
Normal file
326
src/components/Trades.tsx
Normal file
@@ -0,0 +1,326 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { ArrowLeftRight, Check, X, Clock, History, Plus, Package } from 'lucide-react';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import {
|
||||||
|
getTrades,
|
||||||
|
getTradeHistory,
|
||||||
|
acceptTrade,
|
||||||
|
declineTrade,
|
||||||
|
cancelTrade,
|
||||||
|
Trade,
|
||||||
|
TradeItem,
|
||||||
|
} from '../services/tradesService';
|
||||||
|
import { getCardsByIds } from '../services/api';
|
||||||
|
import { Card } from '../types';
|
||||||
|
|
||||||
|
type Tab = 'pending' | 'history';
|
||||||
|
|
||||||
|
interface TradeWithCards extends Trade {
|
||||||
|
cardDetails?: Map<string, Card>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Trades() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [activeTab, setActiveTab] = useState<Tab>('pending');
|
||||||
|
const [pendingTrades, setPendingTrades] = useState<TradeWithCards[]>([]);
|
||||||
|
const [tradeHistory, setTradeHistory] = useState<TradeWithCards[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [processingTradeId, setProcessingTradeId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
loadTrades();
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const loadTrades = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [pending, history] = await Promise.all([
|
||||||
|
getTrades(user.id).then((trades) => trades.filter((t) => t.status === 'pending')),
|
||||||
|
getTradeHistory(user.id),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Load card details for all trades
|
||||||
|
const allCardIds = new Set<string>();
|
||||||
|
[...pending, ...history].forEach((trade) => {
|
||||||
|
trade.items?.forEach((item) => allCardIds.add(item.card_id));
|
||||||
|
});
|
||||||
|
|
||||||
|
let cardDetails = new Map<string, Card>();
|
||||||
|
if (allCardIds.size > 0) {
|
||||||
|
const cards = await getCardsByIds(Array.from(allCardIds));
|
||||||
|
cards.forEach((card) => cardDetails.set(card.id, card));
|
||||||
|
}
|
||||||
|
|
||||||
|
setPendingTrades(pending.map((t) => ({ ...t, cardDetails })));
|
||||||
|
setTradeHistory(history.map((t) => ({ ...t, cardDetails })));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading trades:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAccept = async (tradeId: string) => {
|
||||||
|
setProcessingTradeId(tradeId);
|
||||||
|
try {
|
||||||
|
const success = await acceptTrade(tradeId);
|
||||||
|
if (success) {
|
||||||
|
await loadTrades();
|
||||||
|
} else {
|
||||||
|
alert('Failed to execute trade. Please check your collection.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error accepting trade:', error);
|
||||||
|
alert('Error accepting trade');
|
||||||
|
} finally {
|
||||||
|
setProcessingTradeId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDecline = async (tradeId: string) => {
|
||||||
|
setProcessingTradeId(tradeId);
|
||||||
|
try {
|
||||||
|
await declineTrade(tradeId);
|
||||||
|
await loadTrades();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error declining trade:', error);
|
||||||
|
} finally {
|
||||||
|
setProcessingTradeId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancel = async (tradeId: string) => {
|
||||||
|
if (!confirm('Cancel this trade offer?')) return;
|
||||||
|
setProcessingTradeId(tradeId);
|
||||||
|
try {
|
||||||
|
await cancelTrade(tradeId);
|
||||||
|
await loadTrades();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error cancelling trade:', error);
|
||||||
|
} finally {
|
||||||
|
setProcessingTradeId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusColor = (status: Trade['status']) => {
|
||||||
|
switch (status) {
|
||||||
|
case 'accepted':
|
||||||
|
return 'text-green-400';
|
||||||
|
case 'declined':
|
||||||
|
return 'text-red-400';
|
||||||
|
case 'cancelled':
|
||||||
|
return 'text-gray-400';
|
||||||
|
default:
|
||||||
|
return 'text-yellow-400';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderTradeItems = (
|
||||||
|
items: TradeItem[] | undefined,
|
||||||
|
ownerId: string,
|
||||||
|
cardDetails: Map<string, Card> | undefined,
|
||||||
|
label: string
|
||||||
|
) => {
|
||||||
|
const ownerItems = items?.filter((i) => i.owner_id === ownerId) || [];
|
||||||
|
if (ownerItems.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="text-gray-500 text-sm italic">
|
||||||
|
{label}: Nothing (gift)
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="text-gray-400 text-sm mb-1">{label}:</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{ownerItems.map((item) => {
|
||||||
|
const card = cardDetails?.get(item.card_id);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.id}
|
||||||
|
className="flex items-center gap-2 bg-gray-700 px-2 py-1 rounded text-sm"
|
||||||
|
>
|
||||||
|
{card?.image_uris?.small && (
|
||||||
|
<img
|
||||||
|
src={card.image_uris.small}
|
||||||
|
alt={card.name}
|
||||||
|
className="w-8 h-11 rounded"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<span>{card?.name || item.card_id}</span>
|
||||||
|
{item.quantity > 1 && (
|
||||||
|
<span className="text-gray-400">x{item.quantity}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderTrade = (trade: TradeWithCards, showActions: boolean) => {
|
||||||
|
const isSender = trade.sender_id === user?.id;
|
||||||
|
const otherUser = isSender ? trade.receiver : trade.sender;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={trade.id} className="bg-gray-800 rounded-lg p-4 space-y-4">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ArrowLeftRight size={18} className="text-blue-400" />
|
||||||
|
<span className="font-medium">
|
||||||
|
{isSender ? `To: ${otherUser?.username}` : `From: ${otherUser?.username}`}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className={`text-sm capitalize ${getStatusColor(trade.status)}`}>
|
||||||
|
{trade.status}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Trade Items */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
{renderTradeItems(
|
||||||
|
trade.items,
|
||||||
|
trade.sender_id,
|
||||||
|
trade.cardDetails,
|
||||||
|
isSender ? 'You give' : 'They give'
|
||||||
|
)}
|
||||||
|
{renderTradeItems(
|
||||||
|
trade.items,
|
||||||
|
trade.receiver_id,
|
||||||
|
trade.cardDetails,
|
||||||
|
isSender ? 'You receive' : 'They receive'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Message */}
|
||||||
|
{trade.message && (
|
||||||
|
<div className="text-gray-400 text-sm">
|
||||||
|
<span className="text-gray-500">Message:</span> {trade.message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
{showActions && trade.status === 'pending' && (
|
||||||
|
<div className="flex gap-2 pt-2 border-t border-gray-700">
|
||||||
|
{isSender ? (
|
||||||
|
<button
|
||||||
|
onClick={() => handleCancel(trade.id)}
|
||||||
|
disabled={processingTradeId === trade.id}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
|
||||||
|
>
|
||||||
|
<X size={16} />
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => handleAccept(trade.id)}
|
||||||
|
disabled={processingTradeId === trade.id}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 rounded-lg transition text-sm"
|
||||||
|
>
|
||||||
|
{processingTradeId === trade.id ? (
|
||||||
|
<div className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white"></div>
|
||||||
|
) : (
|
||||||
|
<Check size={16} />
|
||||||
|
)}
|
||||||
|
Accept
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDecline(trade.id)}
|
||||||
|
disabled={processingTradeId === trade.id}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 bg-red-600 hover:bg-red-700 rounded-lg transition text-sm"
|
||||||
|
>
|
||||||
|
<X size={16} />
|
||||||
|
Decline
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Timestamp */}
|
||||||
|
<div className="text-gray-500 text-xs">
|
||||||
|
{new Date(trade.created_at || '').toLocaleDateString()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
|
||||||
|
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-900 text-white p-6">
|
||||||
|
<div className="max-w-3xl mx-auto">
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h1 className="text-3xl font-bold">Trades</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex gap-2 mb-6">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('pending')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||||
|
activeTab === 'pending'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Clock size={18} />
|
||||||
|
Pending ({pendingTrades.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('history')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||||
|
activeTab === 'history'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<History size={18} />
|
||||||
|
History
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Pending Trades */}
|
||||||
|
{activeTab === 'pending' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{pendingTrades.length === 0 ? (
|
||||||
|
<div className="text-center py-12">
|
||||||
|
<Package size={48} className="mx-auto text-gray-600 mb-4" />
|
||||||
|
<p className="text-gray-400">No pending trades</p>
|
||||||
|
<p className="text-gray-500 text-sm mt-2">
|
||||||
|
Visit a friend's collection to propose a trade
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
pendingTrades.map((trade) => renderTrade(trade, true))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Trade History */}
|
||||||
|
{activeTab === 'history' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{tradeHistory.length === 0 ? (
|
||||||
|
<p className="text-gray-400 text-center py-8">No trade history yet</p>
|
||||||
|
) : (
|
||||||
|
tradeHistory.map((trade) => renderTrade(trade, false))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
412
src/examples/CollectionIntegrationExample.tsx
Normal file
412
src/examples/CollectionIntegrationExample.tsx
Normal file
@@ -0,0 +1,412 @@
|
|||||||
|
/**
|
||||||
|
* EXAMPLE FILE - Collection Integration Examples
|
||||||
|
*
|
||||||
|
* This file demonstrates how to integrate the collection service
|
||||||
|
* into your components. These are complete, working examples that
|
||||||
|
* can be used as templates for implementing the collection features.
|
||||||
|
*
|
||||||
|
* DO NOT DELETE - Reference for frontend integration
|
||||||
|
*/
|
||||||
|
|
||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { useCollection } from '../hooks/useCollection';
|
||||||
|
import { CardOwnershipInfo, MissingCardInfo } from '../services/collectionService';
|
||||||
|
import { Card } from '../types';
|
||||||
|
import { Plus, CheckCircle, AlertCircle } from 'lucide-react';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example 1: Display Missing Cards Badge
|
||||||
|
* Shows a badge indicating how many cards are missing from collection
|
||||||
|
*/
|
||||||
|
export function MissingCardsBadge({ deckId }: { deckId: string }) {
|
||||||
|
const { getMissingCards, loading } = useCollection();
|
||||||
|
const [missingCount, setMissingCount] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchMissing = async () => {
|
||||||
|
const missing = await getMissingCards(deckId);
|
||||||
|
if (missing) {
|
||||||
|
setMissingCount(missing.length);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchMissing();
|
||||||
|
}, [deckId, getMissingCards]);
|
||||||
|
|
||||||
|
if (loading) return <span className="text-gray-400">...</span>;
|
||||||
|
|
||||||
|
return missingCount > 0 ? (
|
||||||
|
<span className="bg-red-500 text-white px-2 py-1 rounded text-sm">
|
||||||
|
{missingCount} cards missing
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="bg-green-500 text-white px-2 py-1 rounded text-sm flex items-center gap-1">
|
||||||
|
<CheckCircle size={16} />
|
||||||
|
Complete
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example 2: Card Ownership Indicator
|
||||||
|
* Shows whether a specific card is owned and in what quantity
|
||||||
|
*/
|
||||||
|
interface CardOwnershipIndicatorProps {
|
||||||
|
cardId: string;
|
||||||
|
quantityNeeded: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CardOwnershipIndicator({ cardId, quantityNeeded }: CardOwnershipIndicatorProps) {
|
||||||
|
const { checkCardOwnership } = useCollection();
|
||||||
|
const [owned, setOwned] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const check = async () => {
|
||||||
|
const card = await checkCardOwnership(cardId);
|
||||||
|
setOwned(card?.quantity || 0);
|
||||||
|
};
|
||||||
|
check();
|
||||||
|
}, [cardId, checkCardOwnership]);
|
||||||
|
|
||||||
|
const hasEnough = owned >= quantityNeeded;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex items-center gap-2 ${hasEnough ? 'text-green-500' : 'text-red-500'}`}>
|
||||||
|
{hasEnough ? <CheckCircle size={16} /> : <AlertCircle size={16} />}
|
||||||
|
<span>
|
||||||
|
{owned} / {quantityNeeded} owned
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example 3: Add Single Card Button
|
||||||
|
* Button to add a specific card to collection
|
||||||
|
*/
|
||||||
|
interface AddCardButtonProps {
|
||||||
|
cardId: string;
|
||||||
|
cardName: string;
|
||||||
|
quantity?: number;
|
||||||
|
onSuccess?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AddCardButton({ cardId, cardName, quantity = 1, onSuccess }: AddCardButtonProps) {
|
||||||
|
const { addCard, loading, error, clearError } = useCollection();
|
||||||
|
|
||||||
|
const handleAdd = async () => {
|
||||||
|
clearError();
|
||||||
|
const success = await addCard(cardId, quantity);
|
||||||
|
if (success) {
|
||||||
|
alert(`Added ${quantity}x ${cardName} to collection!`);
|
||||||
|
onSuccess?.();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
onClick={handleAdd}
|
||||||
|
disabled={loading}
|
||||||
|
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<Plus size={16} />
|
||||||
|
{loading ? 'Adding...' : `Add ${quantity > 1 ? `${quantity}x ` : ''}to Collection`}
|
||||||
|
</button>
|
||||||
|
{error && <p className="text-red-500 text-sm mt-1">{error}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example 4: Add All Missing Cards Button
|
||||||
|
* Button to add all missing cards from a deck to collection
|
||||||
|
*/
|
||||||
|
export function AddAllMissingCardsButton({ deckId, onSuccess }: { deckId: string; onSuccess?: () => void }) {
|
||||||
|
const { addMissingDeckCards, loading, error, clearError } = useCollection();
|
||||||
|
const [lastResult, setLastResult] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleAddAll = async () => {
|
||||||
|
clearError();
|
||||||
|
setLastResult(null);
|
||||||
|
|
||||||
|
const results = await addMissingDeckCards(deckId);
|
||||||
|
|
||||||
|
if (results) {
|
||||||
|
const successCount = results.filter(r => r.success).length;
|
||||||
|
const failCount = results.filter(r => !r.success).length;
|
||||||
|
|
||||||
|
let message = `Added ${successCount} cards to collection`;
|
||||||
|
if (failCount > 0) {
|
||||||
|
message += `, ${failCount} failed`;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLastResult(message);
|
||||||
|
|
||||||
|
if (successCount > 0) {
|
||||||
|
onSuccess?.();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
onClick={handleAddAll}
|
||||||
|
disabled={loading}
|
||||||
|
className="px-6 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg flex items-center gap-2 font-semibold"
|
||||||
|
>
|
||||||
|
{loading ? 'Adding Cards...' : 'Add All Missing Cards to Collection'}
|
||||||
|
</button>
|
||||||
|
{lastResult && <p className="text-green-400 text-sm mt-2">{lastResult}</p>}
|
||||||
|
{error && <p className="text-red-500 text-sm mt-2">{error}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example 5: Deck Card List with Collection Status
|
||||||
|
* Shows all cards in a deck with their collection status
|
||||||
|
*/
|
||||||
|
interface DeckCardWithStatusProps {
|
||||||
|
deckId: string;
|
||||||
|
cards: Array<{ card: Card; quantity: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DeckCardListWithStatus({ deckId, cards }: DeckCardWithStatusProps) {
|
||||||
|
const { getDeckOwnership, loading } = useCollection();
|
||||||
|
const [ownership, setOwnership] = useState<CardOwnershipInfo[]>([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchOwnership = async () => {
|
||||||
|
const data = await getDeckOwnership(deckId);
|
||||||
|
if (data) setOwnership(data);
|
||||||
|
};
|
||||||
|
fetchOwnership();
|
||||||
|
}, [deckId, getDeckOwnership]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <div className="text-gray-400">Loading collection status...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ownershipMap = new Map(ownership.map(o => [o.card_id, o]));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{cards.map(({ card, quantity }) => {
|
||||||
|
const status = ownershipMap.get(card.id);
|
||||||
|
const isOwned = status?.owned || false;
|
||||||
|
const quantityOwned = status?.quantity_in_collection || 0;
|
||||||
|
const quantityNeeded = status?.quantity_needed || 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={card.id} className="flex items-center gap-4 bg-gray-800 p-4 rounded-lg">
|
||||||
|
<img
|
||||||
|
src={card.image_uris?.art_crop}
|
||||||
|
alt={card.name}
|
||||||
|
className="w-16 h-16 rounded object-cover"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex-1">
|
||||||
|
<h3 className="font-semibold">{card.name}</h3>
|
||||||
|
<p className="text-sm text-gray-400">
|
||||||
|
Need: {quantity} | Owned: {quantityOwned}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isOwned ? (
|
||||||
|
<span className="text-green-500 flex items-center gap-1">
|
||||||
|
<CheckCircle size={20} />
|
||||||
|
Complete
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<span className="text-red-500 flex items-center gap-1">
|
||||||
|
<AlertCircle size={20} />
|
||||||
|
Need {quantityNeeded} more
|
||||||
|
</span>
|
||||||
|
<AddCardButton
|
||||||
|
cardId={card.id}
|
||||||
|
cardName={card.name}
|
||||||
|
quantity={quantityNeeded}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example 6: Bulk Add with Preview
|
||||||
|
* Shows missing cards and allows bulk add with preview
|
||||||
|
*/
|
||||||
|
export function BulkAddWithPreview({ deckId }: { deckId: string }) {
|
||||||
|
const { getMissingCards, addCardsBulk, loading, error } = useCollection();
|
||||||
|
const [missingCards, setMissingCards] = useState<MissingCardInfo[]>([]);
|
||||||
|
const [showPreview, setShowPreview] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchMissing = async () => {
|
||||||
|
const missing = await getMissingCards(deckId);
|
||||||
|
if (missing) setMissingCards(missing);
|
||||||
|
};
|
||||||
|
fetchMissing();
|
||||||
|
}, [deckId, getMissingCards]);
|
||||||
|
|
||||||
|
const handleBulkAdd = async () => {
|
||||||
|
const cardsToAdd = missingCards.map(card => ({
|
||||||
|
card_id: card.card_id,
|
||||||
|
quantity: card.quantity_needed,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const results = await addCardsBulk(cardsToAdd);
|
||||||
|
|
||||||
|
if (results) {
|
||||||
|
const successCount = results.filter(r => r.success).length;
|
||||||
|
alert(`Successfully added ${successCount} cards to collection!`);
|
||||||
|
setMissingCards([]);
|
||||||
|
setShowPreview(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (missingCards.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="bg-green-500/10 border border-green-500 rounded-lg p-4 text-green-400">
|
||||||
|
All cards from this deck are in your collection!
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h3 className="text-xl font-bold">Missing Cards: {missingCards.length}</h3>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowPreview(!showPreview)}
|
||||||
|
className="text-blue-400 hover:text-blue-300"
|
||||||
|
>
|
||||||
|
{showPreview ? 'Hide' : 'Show'} Preview
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showPreview && (
|
||||||
|
<div className="bg-gray-800 rounded-lg p-4 space-y-2">
|
||||||
|
{missingCards.map(card => (
|
||||||
|
<div key={card.card_id} className="flex justify-between text-sm">
|
||||||
|
<span>{card.card_id}</span>
|
||||||
|
<span className="text-gray-400">
|
||||||
|
Need {card.quantity_needed} (have {card.quantity_in_collection})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={handleBulkAdd}
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full px-6 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg font-semibold"
|
||||||
|
>
|
||||||
|
{loading ? 'Adding...' : `Add All ${missingCards.length} Missing Cards`}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-500/10 border border-red-500 rounded-lg p-4 text-red-400">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example 7: Complete Deck Editor Integration
|
||||||
|
* Full example of a deck editor with collection integration
|
||||||
|
*/
|
||||||
|
interface CompleteDeckEditorExampleProps {
|
||||||
|
deckId: string;
|
||||||
|
deckName: string;
|
||||||
|
cards: Array<{ card: Card; quantity: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CompleteDeckEditorExample({ deckId, deckName, cards }: CompleteDeckEditorExampleProps) {
|
||||||
|
const { getDeckOwnership, addMissingDeckCards, loading } = useCollection();
|
||||||
|
const [ownership, setOwnership] = useState<CardOwnershipInfo[]>([]);
|
||||||
|
const [refreshKey, setRefreshKey] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchOwnership = async () => {
|
||||||
|
const data = await getDeckOwnership(deckId);
|
||||||
|
if (data) setOwnership(data);
|
||||||
|
};
|
||||||
|
fetchOwnership();
|
||||||
|
}, [deckId, getDeckOwnership, refreshKey]);
|
||||||
|
|
||||||
|
const handleRefresh = () => setRefreshKey(prev => prev + 1);
|
||||||
|
|
||||||
|
const missingCount = ownership.filter(o => !o.owned).length;
|
||||||
|
const totalCards = cards.length;
|
||||||
|
const ownedCount = totalCards - missingCount;
|
||||||
|
const completionPercent = totalCards > 0 ? Math.round((ownedCount / totalCards) * 100) : 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-4xl mx-auto p-6 space-y-6">
|
||||||
|
{/* Header with stats */}
|
||||||
|
<div className="bg-gray-800 rounded-lg p-6">
|
||||||
|
<h1 className="text-3xl font-bold mb-4">{deckName}</h1>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-3 gap-4 mb-4">
|
||||||
|
<div className="bg-gray-700 rounded p-3">
|
||||||
|
<div className="text-sm text-gray-400">Total Cards</div>
|
||||||
|
<div className="text-2xl font-bold">{totalCards}</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-gray-700 rounded p-3">
|
||||||
|
<div className="text-sm text-gray-400">Owned</div>
|
||||||
|
<div className="text-2xl font-bold text-green-500">{ownedCount}</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-gray-700 rounded p-3">
|
||||||
|
<div className="text-sm text-gray-400">Missing</div>
|
||||||
|
<div className="text-2xl font-bold text-red-500">{missingCount}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Progress bar */}
|
||||||
|
<div className="w-full bg-gray-700 rounded-full h-4 mb-4">
|
||||||
|
<div
|
||||||
|
className="bg-green-500 h-4 rounded-full transition-all"
|
||||||
|
style={{ width: `${completionPercent}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Action buttons */}
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{missingCount > 0 && (
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
await addMissingDeckCards(deckId);
|
||||||
|
handleRefresh();
|
||||||
|
}}
|
||||||
|
disabled={loading}
|
||||||
|
className="flex-1 px-6 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 rounded-lg font-semibold"
|
||||||
|
>
|
||||||
|
{loading ? 'Adding...' : `Add All ${missingCount} Missing Cards`}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={handleRefresh}
|
||||||
|
className="px-6 py-3 bg-gray-700 hover:bg-gray-600 rounded-lg"
|
||||||
|
>
|
||||||
|
Refresh
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Card list */}
|
||||||
|
<DeckCardListWithStatus deckId={deckId} cards={cards} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
233
src/hooks/useCollection.ts
Normal file
233
src/hooks/useCollection.ts
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import {
|
||||||
|
getUserCollection,
|
||||||
|
getCardInCollection,
|
||||||
|
checkCardsOwnership,
|
||||||
|
getDeckCardOwnership,
|
||||||
|
getMissingCardsFromDeck,
|
||||||
|
addCardToCollection,
|
||||||
|
addCardsToCollectionBulk,
|
||||||
|
addMissingDeckCardsToCollection,
|
||||||
|
removeCardFromCollection,
|
||||||
|
CollectionCard,
|
||||||
|
CardOwnershipInfo,
|
||||||
|
MissingCardInfo,
|
||||||
|
} from '../services/collectionService';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom React hook for managing card collections
|
||||||
|
* Provides state management and loading/error handling for collection operations
|
||||||
|
*/
|
||||||
|
export const useCollection = () => {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear any existing error
|
||||||
|
*/
|
||||||
|
const clearError = useCallback(() => {
|
||||||
|
setError(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user's entire collection
|
||||||
|
*/
|
||||||
|
const getCollection = useCallback(async (): Promise<CollectionCard[] | null> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const collection = await getUserCollection();
|
||||||
|
return collection;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch collection';
|
||||||
|
setError(errorMessage);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a single card is in the collection
|
||||||
|
*/
|
||||||
|
const checkCardOwnership = useCallback(async (cardId: string): Promise<CollectionCard | null> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const card = await getCardInCollection(cardId);
|
||||||
|
return card;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to check card ownership';
|
||||||
|
setError(errorMessage);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check ownership for multiple cards
|
||||||
|
*/
|
||||||
|
const checkMultipleCardsOwnership = useCallback(
|
||||||
|
async (cardIds: string[]): Promise<Map<string, number> | null> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const ownershipMap = await checkCardsOwnership(cardIds);
|
||||||
|
return ownershipMap;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to check cards ownership';
|
||||||
|
setError(errorMessage);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get detailed ownership info for all cards in a deck
|
||||||
|
*/
|
||||||
|
const getDeckOwnership = useCallback(
|
||||||
|
async (deckId: string): Promise<CardOwnershipInfo[] | null> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const ownershipInfo = await getDeckCardOwnership(deckId);
|
||||||
|
return ownershipInfo;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to get deck ownership info';
|
||||||
|
setError(errorMessage);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get list of missing cards from a deck
|
||||||
|
*/
|
||||||
|
const getMissingCards = useCallback(
|
||||||
|
async (deckId: string): Promise<MissingCardInfo[] | null> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const missingCards = await getMissingCardsFromDeck(deckId);
|
||||||
|
return missingCards;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to get missing cards';
|
||||||
|
setError(errorMessage);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a single card to collection
|
||||||
|
*/
|
||||||
|
const addCard = useCallback(
|
||||||
|
async (cardId: string, quantity: number = 1): Promise<boolean> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await addCardToCollection(cardId, quantity);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to add card to collection';
|
||||||
|
setError(errorMessage);
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add multiple cards to collection in bulk
|
||||||
|
*/
|
||||||
|
const addCardsBulk = useCallback(
|
||||||
|
async (
|
||||||
|
cards: Array<{ card_id: string; quantity: number }>
|
||||||
|
): Promise<Array<{ card_id: string; success: boolean; error?: string }> | null> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const results = await addCardsToCollectionBulk(cards);
|
||||||
|
return results;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to add cards to collection';
|
||||||
|
setError(errorMessage);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add all missing cards from a deck to collection
|
||||||
|
*/
|
||||||
|
const addMissingDeckCards = useCallback(
|
||||||
|
async (
|
||||||
|
deckId: string
|
||||||
|
): Promise<Array<{ card_id: string; success: boolean; error?: string }> | null> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const results = await addMissingDeckCardsToCollection(deckId);
|
||||||
|
return results;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to add missing cards';
|
||||||
|
setError(errorMessage);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a card from collection
|
||||||
|
*/
|
||||||
|
const removeCard = useCallback(
|
||||||
|
async (cardId: string, quantity?: number): Promise<boolean> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await removeCardFromCollection(cardId, quantity);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to remove card from collection';
|
||||||
|
setError(errorMessage);
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
clearError,
|
||||||
|
getCollection,
|
||||||
|
checkCardOwnership,
|
||||||
|
checkMultipleCardsOwnership,
|
||||||
|
getDeckOwnership,
|
||||||
|
getMissingCards,
|
||||||
|
addCard,
|
||||||
|
addCardsBulk,
|
||||||
|
addMissingDeckCards,
|
||||||
|
removeCard,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -143,6 +143,7 @@ export type Database = {
|
|||||||
theme_color: string | null
|
theme_color: string | null
|
||||||
updated_at: string | null
|
updated_at: string | null
|
||||||
username: string | null
|
username: string | null
|
||||||
|
collection_visibility: 'public' | 'friends' | 'private' | null
|
||||||
}
|
}
|
||||||
Insert: {
|
Insert: {
|
||||||
created_at?: string | null
|
created_at?: string | null
|
||||||
@@ -150,6 +151,7 @@ export type Database = {
|
|||||||
theme_color?: string | null
|
theme_color?: string | null
|
||||||
updated_at?: string | null
|
updated_at?: string | null
|
||||||
username?: string | null
|
username?: string | null
|
||||||
|
collection_visibility?: 'public' | 'friends' | 'private' | null
|
||||||
}
|
}
|
||||||
Update: {
|
Update: {
|
||||||
created_at?: string | null
|
created_at?: string | null
|
||||||
@@ -157,9 +159,139 @@ export type Database = {
|
|||||||
theme_color?: string | null
|
theme_color?: string | null
|
||||||
updated_at?: string | null
|
updated_at?: string | null
|
||||||
username?: string | null
|
username?: string | null
|
||||||
|
collection_visibility?: 'public' | 'friends' | 'private' | null
|
||||||
}
|
}
|
||||||
Relationships: []
|
Relationships: []
|
||||||
}
|
}
|
||||||
|
friendships: {
|
||||||
|
Row: {
|
||||||
|
id: string
|
||||||
|
requester_id: string
|
||||||
|
addressee_id: string
|
||||||
|
status: 'pending' | 'accepted' | 'declined'
|
||||||
|
created_at: string | null
|
||||||
|
updated_at: string | null
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
id?: string
|
||||||
|
requester_id: string
|
||||||
|
addressee_id: string
|
||||||
|
status?: 'pending' | 'accepted' | 'declined'
|
||||||
|
created_at?: string | null
|
||||||
|
updated_at?: string | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
id?: string
|
||||||
|
requester_id?: string
|
||||||
|
addressee_id?: string
|
||||||
|
status?: 'pending' | 'accepted' | 'declined'
|
||||||
|
created_at?: string | null
|
||||||
|
updated_at?: string | null
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "friendships_requester_id_fkey"
|
||||||
|
columns: ["requester_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "profiles"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: "friendships_addressee_id_fkey"
|
||||||
|
columns: ["addressee_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "profiles"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
trades: {
|
||||||
|
Row: {
|
||||||
|
id: string
|
||||||
|
sender_id: string
|
||||||
|
receiver_id: string
|
||||||
|
status: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||||
|
message: string | null
|
||||||
|
created_at: string | null
|
||||||
|
updated_at: string | null
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
id?: string
|
||||||
|
sender_id: string
|
||||||
|
receiver_id: string
|
||||||
|
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||||
|
message?: string | null
|
||||||
|
created_at?: string | null
|
||||||
|
updated_at?: string | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
id?: string
|
||||||
|
sender_id?: string
|
||||||
|
receiver_id?: string
|
||||||
|
status?: 'pending' | 'accepted' | 'declined' | 'cancelled'
|
||||||
|
message?: string | null
|
||||||
|
created_at?: string | null
|
||||||
|
updated_at?: string | null
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "trades_sender_id_fkey"
|
||||||
|
columns: ["sender_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "profiles"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: "trades_receiver_id_fkey"
|
||||||
|
columns: ["receiver_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "profiles"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
trade_items: {
|
||||||
|
Row: {
|
||||||
|
id: string
|
||||||
|
trade_id: string
|
||||||
|
owner_id: string
|
||||||
|
card_id: string
|
||||||
|
quantity: number
|
||||||
|
created_at: string | null
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
id?: string
|
||||||
|
trade_id: string
|
||||||
|
owner_id: string
|
||||||
|
card_id: string
|
||||||
|
quantity?: number
|
||||||
|
created_at?: string | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
id?: string
|
||||||
|
trade_id?: string
|
||||||
|
owner_id?: string
|
||||||
|
card_id?: string
|
||||||
|
quantity?: number
|
||||||
|
created_at?: string | null
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "trade_items_trade_id_fkey"
|
||||||
|
columns: ["trade_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "trades"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: "trade_items_owner_id_fkey"
|
||||||
|
columns: ["owner_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "profiles"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Views: {
|
Views: {
|
||||||
[_ in never]: never
|
[_ in never]: never
|
||||||
@@ -271,4 +403,4 @@ export type CompositeTypes<
|
|||||||
? Database[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"][CompositeTypeName]
|
? Database[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"][CompositeTypeName]
|
||||||
: PublicCompositeTypeNameOrOptions extends keyof PublicSchema["CompositeTypes"]
|
: PublicCompositeTypeNameOrOptions extends keyof PublicSchema["CompositeTypes"]
|
||||||
? PublicSchema["CompositeTypes"][PublicCompositeTypeNameOrOptions]
|
? PublicSchema["CompositeTypes"][PublicCompositeTypeNameOrOptions]
|
||||||
: never
|
: never
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Card } from '../types';
|
import { Card } from '../types';
|
||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
const SCRYFALL_API = 'https://api.scryfall.com';
|
const SCRYFALL_API = 'https://api.scryfall.com';
|
||||||
|
|
||||||
@@ -52,3 +53,127 @@ export const getCardsByIds = async (cardIds: string[]): Promise<Card[]> => {
|
|||||||
|
|
||||||
return allCards;
|
return allCards;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Collection API functions
|
||||||
|
export const getUserCollection = async (userId: string): Promise<Map<string, number>> => {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('card_id, quantity')
|
||||||
|
.eq('user_id', userId);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Error fetching user collection:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a map of card_id to quantity for easy lookup
|
||||||
|
const collectionMap = new Map<string, number>();
|
||||||
|
data?.forEach((item) => {
|
||||||
|
collectionMap.set(item.card_id, item.quantity);
|
||||||
|
});
|
||||||
|
|
||||||
|
return collectionMap;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const addCardToCollection = async (
|
||||||
|
userId: string,
|
||||||
|
cardId: string,
|
||||||
|
quantity: number = 1
|
||||||
|
): Promise<void> => {
|
||||||
|
// Check if card already exists in collection
|
||||||
|
const { data: existing, error: fetchError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('id, quantity')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.eq('card_id', cardId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (fetchError && fetchError.code !== 'PGRST116') {
|
||||||
|
// PGRST116 is "not found" error, which is expected for new cards
|
||||||
|
throw fetchError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
// Update existing card quantity
|
||||||
|
const { error: updateError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.update({
|
||||||
|
quantity: existing.quantity + quantity,
|
||||||
|
updated_at: new Date().toISOString()
|
||||||
|
})
|
||||||
|
.eq('id', existing.id);
|
||||||
|
|
||||||
|
if (updateError) throw updateError;
|
||||||
|
} else {
|
||||||
|
// Insert new card
|
||||||
|
const { error: insertError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.insert({
|
||||||
|
user_id: userId,
|
||||||
|
card_id: cardId,
|
||||||
|
quantity: quantity,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (insertError) throw insertError;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const addMultipleCardsToCollection = async (
|
||||||
|
userId: string,
|
||||||
|
cards: { cardId: string; quantity: number }[]
|
||||||
|
): Promise<void> => {
|
||||||
|
// Fetch existing cards in collection
|
||||||
|
const cardIds = cards.map(c => c.cardId);
|
||||||
|
const { data: existingCards, error: fetchError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('card_id, quantity, id')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.in('card_id', cardIds);
|
||||||
|
|
||||||
|
if (fetchError) throw fetchError;
|
||||||
|
|
||||||
|
const existingMap = new Map<string, { id: string; quantity: number }>();
|
||||||
|
existingCards?.forEach((item) => {
|
||||||
|
existingMap.set(item.card_id, { id: item.id, quantity: item.quantity });
|
||||||
|
});
|
||||||
|
|
||||||
|
const toInsert = [];
|
||||||
|
const toUpdate = [];
|
||||||
|
|
||||||
|
for (const card of cards) {
|
||||||
|
const existing = existingMap.get(card.cardId);
|
||||||
|
if (existing) {
|
||||||
|
toUpdate.push({
|
||||||
|
id: existing.id,
|
||||||
|
quantity: existing.quantity + card.quantity,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
toInsert.push({
|
||||||
|
user_id: userId,
|
||||||
|
card_id: card.cardId,
|
||||||
|
quantity: card.quantity,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perform bulk operations
|
||||||
|
if (toInsert.length > 0) {
|
||||||
|
const { error: insertError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.insert(toInsert);
|
||||||
|
|
||||||
|
if (insertError) throw insertError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toUpdate.length > 0) {
|
||||||
|
for (const update of toUpdate) {
|
||||||
|
const { error: updateError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.update({ quantity: update.quantity, updated_at: update.updated_at })
|
||||||
|
.eq('id', update.id);
|
||||||
|
|
||||||
|
if (updateError) throw updateError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|||||||
546
src/services/collectionService.ts
Normal file
546
src/services/collectionService.ts
Normal file
@@ -0,0 +1,546 @@
|
|||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collection Service
|
||||||
|
* Handles all backend operations related to user card collections
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface CollectionCard {
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
card_id: string;
|
||||||
|
quantity: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MissingCardInfo {
|
||||||
|
card_id: string;
|
||||||
|
quantity_needed: number;
|
||||||
|
quantity_in_collection: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CardOwnershipInfo {
|
||||||
|
card_id: string;
|
||||||
|
owned: boolean;
|
||||||
|
quantity_in_collection: number;
|
||||||
|
quantity_in_deck: number;
|
||||||
|
quantity_needed: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current authenticated user's ID
|
||||||
|
* @throws Error if user is not authenticated
|
||||||
|
*/
|
||||||
|
const getCurrentUserId = async (): Promise<string> => {
|
||||||
|
const { data: { user }, error } = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (error || !user) {
|
||||||
|
throw new Error('User not authenticated');
|
||||||
|
}
|
||||||
|
|
||||||
|
return user.id;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all cards in the user's collection
|
||||||
|
* @returns Array of collection cards with user's ownership info
|
||||||
|
*/
|
||||||
|
export const getUserCollection = async (): Promise<CollectionCard[]> => {
|
||||||
|
try {
|
||||||
|
const userId = await getCurrentUserId();
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('*')
|
||||||
|
.eq('user_id', userId);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to fetch collection: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data || [];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in getUserCollection:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a single card exists in the user's collection
|
||||||
|
* @param cardId - The Scryfall card ID
|
||||||
|
* @returns CollectionCard or null if not found
|
||||||
|
*/
|
||||||
|
export const getCardInCollection = async (cardId: string): Promise<CollectionCard | null> => {
|
||||||
|
try {
|
||||||
|
const userId = await getCurrentUserId();
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('*')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.eq('card_id', cardId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to check card ownership: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in getCardInCollection:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check ownership status for multiple cards
|
||||||
|
* @param cardIds - Array of Scryfall card IDs
|
||||||
|
* @returns Map of card_id to quantity owned
|
||||||
|
*/
|
||||||
|
export const checkCardsOwnership = async (
|
||||||
|
cardIds: string[]
|
||||||
|
): Promise<Map<string, number>> => {
|
||||||
|
try {
|
||||||
|
const userId = await getCurrentUserId();
|
||||||
|
|
||||||
|
// Remove duplicates
|
||||||
|
const uniqueCardIds = [...new Set(cardIds)];
|
||||||
|
|
||||||
|
if (uniqueCardIds.length === 0) {
|
||||||
|
return new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('card_id, quantity')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.in('card_id', uniqueCardIds);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to check cards ownership: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ownershipMap = new Map<string, number>();
|
||||||
|
|
||||||
|
if (data) {
|
||||||
|
data.forEach(item => {
|
||||||
|
ownershipMap.set(item.card_id, item.quantity || 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return ownershipMap;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in checkCardsOwnership:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get detailed card ownership information for a deck
|
||||||
|
* @param deckId - The deck ID to check
|
||||||
|
* @returns Array of CardOwnershipInfo for each card in the deck
|
||||||
|
*/
|
||||||
|
export const getDeckCardOwnership = async (
|
||||||
|
deckId: string
|
||||||
|
): Promise<CardOwnershipInfo[]> => {
|
||||||
|
try {
|
||||||
|
const userId = await getCurrentUserId();
|
||||||
|
|
||||||
|
// First verify the user owns this deck
|
||||||
|
const { data: deck, error: deckError } = await supabase
|
||||||
|
.from('decks')
|
||||||
|
.select('id, user_id')
|
||||||
|
.eq('id', deckId)
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (deckError || !deck) {
|
||||||
|
throw new Error('Deck not found or access denied');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all cards in the deck
|
||||||
|
const { data: deckCards, error: deckCardsError } = await supabase
|
||||||
|
.from('deck_cards')
|
||||||
|
.select('card_id, quantity')
|
||||||
|
.eq('deck_id', deckId);
|
||||||
|
|
||||||
|
if (deckCardsError) {
|
||||||
|
throw new Error(`Failed to fetch deck cards: ${deckCardsError.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!deckCards || deckCards.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a map of card quantities in deck
|
||||||
|
const deckCardMap = new Map<string, number>();
|
||||||
|
deckCards.forEach(card => {
|
||||||
|
const currentQty = deckCardMap.get(card.card_id) || 0;
|
||||||
|
deckCardMap.set(card.card_id, currentQty + (card.quantity || 1));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get ownership info for all cards
|
||||||
|
const cardIds = Array.from(deckCardMap.keys());
|
||||||
|
const ownershipMap = await checkCardsOwnership(cardIds);
|
||||||
|
|
||||||
|
// Build the result
|
||||||
|
const ownershipInfo: CardOwnershipInfo[] = [];
|
||||||
|
|
||||||
|
deckCardMap.forEach((quantityInDeck, cardId) => {
|
||||||
|
const quantityInCollection = ownershipMap.get(cardId) || 0;
|
||||||
|
const quantityNeeded = Math.max(0, quantityInDeck - quantityInCollection);
|
||||||
|
|
||||||
|
ownershipInfo.push({
|
||||||
|
card_id: cardId,
|
||||||
|
owned: quantityInCollection >= quantityInDeck,
|
||||||
|
quantity_in_collection: quantityInCollection,
|
||||||
|
quantity_in_deck: quantityInDeck,
|
||||||
|
quantity_needed: quantityNeeded,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return ownershipInfo;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in getDeckCardOwnership:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get list of missing cards from a deck
|
||||||
|
* @param deckId - The deck ID to check
|
||||||
|
* @returns Array of missing cards with quantity needed
|
||||||
|
*/
|
||||||
|
export const getMissingCardsFromDeck = async (
|
||||||
|
deckId: string
|
||||||
|
): Promise<MissingCardInfo[]> => {
|
||||||
|
try {
|
||||||
|
const ownershipInfo = await getDeckCardOwnership(deckId);
|
||||||
|
|
||||||
|
return ownershipInfo
|
||||||
|
.filter(info => !info.owned)
|
||||||
|
.map(info => ({
|
||||||
|
card_id: info.card_id,
|
||||||
|
quantity_needed: info.quantity_needed,
|
||||||
|
quantity_in_collection: info.quantity_in_collection,
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in getMissingCardsFromDeck:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a single card to the user's collection
|
||||||
|
* If the card already exists, increment its quantity
|
||||||
|
* @param cardId - The Scryfall card ID
|
||||||
|
* @param quantity - The quantity to add (default: 1)
|
||||||
|
* @returns The updated or created collection card
|
||||||
|
*/
|
||||||
|
export const addCardToCollection = async (
|
||||||
|
cardId: string,
|
||||||
|
quantity: number = 1
|
||||||
|
): Promise<CollectionCard> => {
|
||||||
|
try {
|
||||||
|
if (!cardId || cardId.trim() === '') {
|
||||||
|
throw new Error('Invalid card ID');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (quantity < 1) {
|
||||||
|
throw new Error('Quantity must be at least 1');
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = await getCurrentUserId();
|
||||||
|
|
||||||
|
// Check if card already exists in collection
|
||||||
|
const existingCard = await getCardInCollection(cardId);
|
||||||
|
|
||||||
|
if (existingCard) {
|
||||||
|
// Update existing card quantity
|
||||||
|
const newQuantity = existingCard.quantity + quantity;
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.update({
|
||||||
|
quantity: newQuantity,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq('id', existingCard.id)
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to update card quantity: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
} else {
|
||||||
|
// Insert new card
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.insert({
|
||||||
|
user_id: userId,
|
||||||
|
card_id: cardId,
|
||||||
|
quantity: quantity,
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to add card to collection: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in addCardToCollection:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add multiple cards to the user's collection in bulk
|
||||||
|
* @param cards - Array of {card_id, quantity} objects
|
||||||
|
* @returns Array of results with success/failure status for each card
|
||||||
|
*/
|
||||||
|
export const addCardsToCollectionBulk = async (
|
||||||
|
cards: Array<{ card_id: string; quantity: number }>
|
||||||
|
): Promise<Array<{ card_id: string; success: boolean; error?: string }>> => {
|
||||||
|
try {
|
||||||
|
if (!cards || cards.length === 0) {
|
||||||
|
throw new Error('No cards provided');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate all cards first
|
||||||
|
const validationErrors: string[] = [];
|
||||||
|
cards.forEach((card, index) => {
|
||||||
|
if (!card.card_id || card.card_id.trim() === '') {
|
||||||
|
validationErrors.push(`Card at index ${index} has invalid ID`);
|
||||||
|
}
|
||||||
|
if (card.quantity < 1) {
|
||||||
|
validationErrors.push(`Card at index ${index} has invalid quantity`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (validationErrors.length > 0) {
|
||||||
|
throw new Error(`Validation failed: ${validationErrors.join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = await getCurrentUserId();
|
||||||
|
|
||||||
|
// Get current collection state for all cards
|
||||||
|
const cardIds = cards.map(c => c.card_id);
|
||||||
|
|
||||||
|
// Prepare updates and inserts
|
||||||
|
const toUpdate: Array<{ id: string; card_id: string; quantity: number }> = [];
|
||||||
|
const toInsert: Array<{ user_id: string; card_id: string; quantity: number }> = [];
|
||||||
|
|
||||||
|
// First, get existing collection entries for update
|
||||||
|
const { data: existingCards, error: fetchError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('id, card_id, quantity')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.in('card_id', cardIds);
|
||||||
|
|
||||||
|
if (fetchError) {
|
||||||
|
throw new Error(`Failed to fetch existing cards: ${fetchError.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingCardsMap = new Map(
|
||||||
|
(existingCards || []).map(card => [card.card_id, card])
|
||||||
|
);
|
||||||
|
|
||||||
|
// Categorize cards for update or insert
|
||||||
|
cards.forEach(card => {
|
||||||
|
const existing = existingCardsMap.get(card.card_id);
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
toUpdate.push({
|
||||||
|
id: existing.id,
|
||||||
|
card_id: card.card_id,
|
||||||
|
quantity: existing.quantity + card.quantity,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
toInsert.push({
|
||||||
|
user_id: userId,
|
||||||
|
card_id: card.card_id,
|
||||||
|
quantity: card.quantity,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const results: Array<{ card_id: string; success: boolean; error?: string }> = [];
|
||||||
|
|
||||||
|
// Process updates
|
||||||
|
for (const updateCard of toUpdate) {
|
||||||
|
try {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.update({
|
||||||
|
quantity: updateCard.quantity,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq('id', updateCard.id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
results.push({
|
||||||
|
card_id: updateCard.card_id,
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
results.push({
|
||||||
|
card_id: updateCard.card_id,
|
||||||
|
success: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
results.push({
|
||||||
|
card_id: updateCard.card_id,
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process inserts in batches (Supabase recommends batches of 1000)
|
||||||
|
const batchSize = 1000;
|
||||||
|
for (let i = 0; i < toInsert.length; i += batchSize) {
|
||||||
|
const batch = toInsert.slice(i, i + batchSize);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.insert(batch);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
// If batch fails, mark all as failed
|
||||||
|
batch.forEach(card => {
|
||||||
|
results.push({
|
||||||
|
card_id: card.card_id,
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Mark all as success
|
||||||
|
batch.forEach(card => {
|
||||||
|
results.push({
|
||||||
|
card_id: card.card_id,
|
||||||
|
success: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// If batch fails with exception, mark all as failed
|
||||||
|
batch.forEach(card => {
|
||||||
|
results.push({
|
||||||
|
card_id: card.card_id,
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in addCardsToCollectionBulk:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add all missing cards from a deck to the user's collection
|
||||||
|
* @param deckId - The deck ID
|
||||||
|
* @returns Array of results with success/failure status for each card
|
||||||
|
*/
|
||||||
|
export const addMissingDeckCardsToCollection = async (
|
||||||
|
deckId: string
|
||||||
|
): Promise<Array<{ card_id: string; success: boolean; error?: string }>> => {
|
||||||
|
try {
|
||||||
|
const userId = await getCurrentUserId();
|
||||||
|
|
||||||
|
// Verify deck ownership
|
||||||
|
const { data: deck, error: deckError } = await supabase
|
||||||
|
.from('decks')
|
||||||
|
.select('id')
|
||||||
|
.eq('id', deckId)
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (deckError || !deck) {
|
||||||
|
throw new Error('Deck not found or access denied');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get missing cards
|
||||||
|
const missingCards = await getMissingCardsFromDeck(deckId);
|
||||||
|
|
||||||
|
if (missingCards.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to format for bulk add
|
||||||
|
const cardsToAdd = missingCards.map(card => ({
|
||||||
|
card_id: card.card_id,
|
||||||
|
quantity: card.quantity_needed,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return await addCardsToCollectionBulk(cardsToAdd);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in addMissingDeckCardsToCollection:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a card from the user's collection
|
||||||
|
* @param cardId - The Scryfall card ID
|
||||||
|
* @param quantity - The quantity to remove (default: all)
|
||||||
|
* @returns true if successful
|
||||||
|
*/
|
||||||
|
export const removeCardFromCollection = async (
|
||||||
|
cardId: string,
|
||||||
|
quantity?: number
|
||||||
|
): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
const existingCard = await getCardInCollection(cardId);
|
||||||
|
|
||||||
|
if (!existingCard) {
|
||||||
|
throw new Error('Card not found in collection');
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no quantity specified or quantity >= existing, delete the entry
|
||||||
|
if (!quantity || quantity >= existingCard.quantity) {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.delete()
|
||||||
|
.eq('id', existingCard.id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to remove card: ${error.message}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Otherwise, decrease the quantity
|
||||||
|
const newQuantity = existingCard.quantity - quantity;
|
||||||
|
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.update({
|
||||||
|
quantity: newQuantity,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq('id', existingCard.id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to update card quantity: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in removeCardFromCollection:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
202
src/services/friendsService.ts
Normal file
202
src/services/friendsService.ts
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
|
export interface Friend {
|
||||||
|
id: string;
|
||||||
|
odship_id: string;
|
||||||
|
username: string | null;
|
||||||
|
status: 'pending' | 'accepted' | 'declined';
|
||||||
|
isRequester: boolean;
|
||||||
|
created_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendshipWithProfile {
|
||||||
|
id: string;
|
||||||
|
requester_id: string;
|
||||||
|
addressee_id: string;
|
||||||
|
status: 'pending' | 'accepted' | 'declined';
|
||||||
|
created_at: string | null;
|
||||||
|
requester: { username: string | null };
|
||||||
|
addressee: { username: string | null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all friends (accepted friendships)
|
||||||
|
export async function getFriends(userId: string): Promise<Friend[]> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.select(`
|
||||||
|
id,
|
||||||
|
requester_id,
|
||||||
|
addressee_id,
|
||||||
|
status,
|
||||||
|
created_at,
|
||||||
|
requester:profiles!friendships_requester_id_fkey(username),
|
||||||
|
addressee:profiles!friendships_addressee_id_fkey(username)
|
||||||
|
`)
|
||||||
|
.eq('status', 'accepted')
|
||||||
|
.or(`requester_id.eq.${userId},addressee_id.eq.${userId}`);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
return (data as unknown as FriendshipWithProfile[]).map((f) => {
|
||||||
|
const isRequester = f.requester_id === userId;
|
||||||
|
return {
|
||||||
|
id: isRequester ? f.addressee_id : f.requester_id,
|
||||||
|
friendshipId: f.id,
|
||||||
|
username: isRequester ? f.addressee?.username : f.requester?.username,
|
||||||
|
status: f.status,
|
||||||
|
isRequester,
|
||||||
|
created_at: f.created_at,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get pending friend requests (received)
|
||||||
|
export async function getPendingRequests(userId: string): Promise<Friend[]> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.select(`
|
||||||
|
id,
|
||||||
|
requester_id,
|
||||||
|
addressee_id,
|
||||||
|
status,
|
||||||
|
created_at,
|
||||||
|
requester:profiles!friendships_requester_id_fkey(username)
|
||||||
|
`)
|
||||||
|
.eq('status', 'pending')
|
||||||
|
.eq('addressee_id', userId);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
return (data as any[]).map((f) => ({
|
||||||
|
id: f.requester_id,
|
||||||
|
friendshipId: f.id,
|
||||||
|
username: f.requester?.username,
|
||||||
|
status: f.status,
|
||||||
|
isRequester: false,
|
||||||
|
created_at: f.created_at,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get sent friend requests (pending)
|
||||||
|
export async function getSentRequests(userId: string): Promise<Friend[]> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.select(`
|
||||||
|
id,
|
||||||
|
requester_id,
|
||||||
|
addressee_id,
|
||||||
|
status,
|
||||||
|
created_at,
|
||||||
|
addressee:profiles!friendships_addressee_id_fkey(username)
|
||||||
|
`)
|
||||||
|
.eq('status', 'pending')
|
||||||
|
.eq('requester_id', userId);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
return (data as any[]).map((f) => ({
|
||||||
|
id: f.addressee_id,
|
||||||
|
friendshipId: f.id,
|
||||||
|
username: f.addressee?.username,
|
||||||
|
status: f.status,
|
||||||
|
isRequester: true,
|
||||||
|
created_at: f.created_at,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search users by username
|
||||||
|
export async function searchUsers(query: string, currentUserId: string) {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('profiles')
|
||||||
|
.select('id, username')
|
||||||
|
.ilike('username', `%${query}%`)
|
||||||
|
.neq('id', currentUserId)
|
||||||
|
.limit(10);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send friend request
|
||||||
|
export async function sendFriendRequest(requesterId: string, addresseeId: string) {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.insert({
|
||||||
|
requester_id: requesterId,
|
||||||
|
addressee_id: addresseeId,
|
||||||
|
status: 'pending',
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accept friend request
|
||||||
|
export async function acceptFriendRequest(friendshipId: string) {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.update({ status: 'accepted', updated_at: new Date().toISOString() })
|
||||||
|
.eq('id', friendshipId)
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decline friend request
|
||||||
|
export async function declineFriendRequest(friendshipId: string) {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.update({ status: 'declined', updated_at: new Date().toISOString() })
|
||||||
|
.eq('id', friendshipId)
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove friend (delete friendship)
|
||||||
|
export async function removeFriend(friendshipId: string) {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.delete()
|
||||||
|
.eq('id', friendshipId);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if two users are friends
|
||||||
|
export async function areFriends(userId1: string, userId2: string): Promise<boolean> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.select('id')
|
||||||
|
.eq('status', 'accepted')
|
||||||
|
.or(`and(requester_id.eq.${userId1},addressee_id.eq.${userId2}),and(requester_id.eq.${userId2},addressee_id.eq.${userId1})`)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get friendship status between two users
|
||||||
|
export async function getFriendshipStatus(userId1: string, userId2: string) {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('friendships')
|
||||||
|
.select('id, status, requester_id')
|
||||||
|
.or(`and(requester_id.eq.${userId1},addressee_id.eq.${userId2}),and(requester_id.eq.${userId2},addressee_id.eq.${userId1})`)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
if (!data) return { status: 'none' as const, friendshipId: null, isRequester: false };
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: data.status as 'pending' | 'accepted' | 'declined',
|
||||||
|
friendshipId: data.id,
|
||||||
|
isRequester: data.requester_id === userId1,
|
||||||
|
};
|
||||||
|
}
|
||||||
184
src/services/tradesService.ts
Normal file
184
src/services/tradesService.ts
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
|
export interface TradeItem {
|
||||||
|
id: string;
|
||||||
|
trade_id: string;
|
||||||
|
owner_id: string;
|
||||||
|
card_id: string;
|
||||||
|
quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Trade {
|
||||||
|
id: string;
|
||||||
|
sender_id: string;
|
||||||
|
receiver_id: string;
|
||||||
|
status: 'pending' | 'accepted' | 'declined' | 'cancelled';
|
||||||
|
message: string | null;
|
||||||
|
created_at: string | null;
|
||||||
|
updated_at: string | null;
|
||||||
|
sender?: { username: string | null };
|
||||||
|
receiver?: { username: string | null };
|
||||||
|
items?: TradeItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateTradeParams {
|
||||||
|
senderId: string;
|
||||||
|
receiverId: string;
|
||||||
|
message?: string;
|
||||||
|
senderCards: { cardId: string; quantity: number }[];
|
||||||
|
receiverCards: { cardId: string; quantity: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all trades for a user
|
||||||
|
export async function getTrades(userId: string): Promise<Trade[]> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.select(`
|
||||||
|
*,
|
||||||
|
sender:profiles!trades_sender_id_fkey(username),
|
||||||
|
receiver:profiles!trades_receiver_id_fkey(username),
|
||||||
|
items:trade_items(*)
|
||||||
|
`)
|
||||||
|
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||||
|
.order('created_at', { ascending: false });
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data as Trade[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get pending trades for a user
|
||||||
|
export async function getPendingTrades(userId: string): Promise<Trade[]> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.select(`
|
||||||
|
*,
|
||||||
|
sender:profiles!trades_sender_id_fkey(username),
|
||||||
|
receiver:profiles!trades_receiver_id_fkey(username),
|
||||||
|
items:trade_items(*)
|
||||||
|
`)
|
||||||
|
.eq('status', 'pending')
|
||||||
|
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||||
|
.order('created_at', { ascending: false });
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data as Trade[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get trade by ID
|
||||||
|
export async function getTradeById(tradeId: string): Promise<Trade | null> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.select(`
|
||||||
|
*,
|
||||||
|
sender:profiles!trades_sender_id_fkey(username),
|
||||||
|
receiver:profiles!trades_receiver_id_fkey(username),
|
||||||
|
items:trade_items(*)
|
||||||
|
`)
|
||||||
|
.eq('id', tradeId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data as Trade;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new trade with items
|
||||||
|
export async function createTrade(params: CreateTradeParams): Promise<Trade> {
|
||||||
|
const { senderId, receiverId, message, senderCards, receiverCards } = params;
|
||||||
|
|
||||||
|
// Create the trade
|
||||||
|
const { data: trade, error: tradeError } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.insert({
|
||||||
|
sender_id: senderId,
|
||||||
|
receiver_id: receiverId,
|
||||||
|
message,
|
||||||
|
status: 'pending',
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (tradeError) throw tradeError;
|
||||||
|
|
||||||
|
// Add sender's cards
|
||||||
|
const senderItems = senderCards.map((card) => ({
|
||||||
|
trade_id: trade.id,
|
||||||
|
owner_id: senderId,
|
||||||
|
card_id: card.cardId,
|
||||||
|
quantity: card.quantity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Add receiver's cards (what sender wants)
|
||||||
|
const receiverItems = receiverCards.map((card) => ({
|
||||||
|
trade_id: trade.id,
|
||||||
|
owner_id: receiverId,
|
||||||
|
card_id: card.cardId,
|
||||||
|
quantity: card.quantity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const allItems = [...senderItems, ...receiverItems];
|
||||||
|
|
||||||
|
if (allItems.length > 0) {
|
||||||
|
const { error: itemsError } = await supabase
|
||||||
|
.from('trade_items')
|
||||||
|
.insert(allItems);
|
||||||
|
|
||||||
|
if (itemsError) throw itemsError;
|
||||||
|
}
|
||||||
|
|
||||||
|
return trade;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accept a trade (executes the card transfer)
|
||||||
|
export async function acceptTrade(tradeId: string): Promise<boolean> {
|
||||||
|
const { data, error } = await supabase.rpc('execute_trade', {
|
||||||
|
trade_id: tradeId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data as boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decline a trade
|
||||||
|
export async function declineTrade(tradeId: string): Promise<Trade> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.update({ status: 'declined', updated_at: new Date().toISOString() })
|
||||||
|
.eq('id', tradeId)
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel a trade (sender only)
|
||||||
|
export async function cancelTrade(tradeId: string): Promise<Trade> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.update({ status: 'cancelled', updated_at: new Date().toISOString() })
|
||||||
|
.eq('id', tradeId)
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get trade history (completed/cancelled/declined trades)
|
||||||
|
export async function getTradeHistory(userId: string): Promise<Trade[]> {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.select(`
|
||||||
|
*,
|
||||||
|
sender:profiles!trades_sender_id_fkey(username),
|
||||||
|
receiver:profiles!trades_receiver_id_fkey(username),
|
||||||
|
items:trade_items(*)
|
||||||
|
`)
|
||||||
|
.or(`sender_id.eq.${userId},receiver_id.eq.${userId}`)
|
||||||
|
.in('status', ['accepted', 'declined', 'cancelled'])
|
||||||
|
.order('updated_at', { ascending: false })
|
||||||
|
.limit(50);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data as Trade[];
|
||||||
|
}
|
||||||
@@ -16,6 +16,20 @@ export interface Card {
|
|||||||
type_line?: string;
|
type_line?: string;
|
||||||
oracle_text?: string;
|
oracle_text?: string;
|
||||||
colors?: string[];
|
colors?: string[];
|
||||||
|
prices?: {
|
||||||
|
usd?: string;
|
||||||
|
usd_foil?: string;
|
||||||
|
eur?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Collection {
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
card_id: string;
|
||||||
|
quantity: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Deck {
|
export interface Deck {
|
||||||
@@ -34,4 +48,4 @@ export interface CardEntity {
|
|||||||
card_id: string;
|
card_id: string;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
is_commander: boolean;
|
is_commander: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,99 @@
|
|||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from 'vite';
|
||||||
import react from '@vitejs/plugin-react';
|
import react from '@vitejs/plugin-react';
|
||||||
|
import { VitePWA } from 'vite-plugin-pwa';
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [
|
||||||
|
react(),
|
||||||
|
VitePWA({
|
||||||
|
registerType: 'autoUpdate',
|
||||||
|
includeAssets: ['icon.svg'],
|
||||||
|
manifest: {
|
||||||
|
name: 'Deckerr - Card Deck Manager',
|
||||||
|
short_name: 'Deckerr',
|
||||||
|
description: 'Manage your trading card game decks on the go',
|
||||||
|
theme_color: '#0f172a',
|
||||||
|
background_color: '#0f172a',
|
||||||
|
display: 'standalone',
|
||||||
|
orientation: 'portrait',
|
||||||
|
scope: '/',
|
||||||
|
start_url: '/',
|
||||||
|
icons: [
|
||||||
|
{
|
||||||
|
src: 'icon.svg',
|
||||||
|
sizes: '512x512',
|
||||||
|
type: 'image/svg+xml',
|
||||||
|
purpose: 'any'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
src: 'icon.svg',
|
||||||
|
sizes: '512x512',
|
||||||
|
type: 'image/svg+xml',
|
||||||
|
purpose: 'maskable'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
categories: ['games', 'utilities'],
|
||||||
|
shortcuts: [
|
||||||
|
{
|
||||||
|
name: 'My Decks',
|
||||||
|
short_name: 'Decks',
|
||||||
|
description: 'View your deck collection',
|
||||||
|
url: '/?page=home'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Search Cards',
|
||||||
|
short_name: 'Search',
|
||||||
|
description: 'Search for cards',
|
||||||
|
url: '/?page=search'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Life Counter',
|
||||||
|
short_name: 'Life',
|
||||||
|
description: 'Track life totals',
|
||||||
|
url: '/?page=life-counter'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
workbox: {
|
||||||
|
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff,woff2}'],
|
||||||
|
runtimeCaching: [
|
||||||
|
{
|
||||||
|
urlPattern: /^https:\/\/api\.scryfall\.com\/.*/i,
|
||||||
|
handler: 'CacheFirst',
|
||||||
|
options: {
|
||||||
|
cacheName: 'scryfall-cache',
|
||||||
|
expiration: {
|
||||||
|
maxEntries: 500,
|
||||||
|
maxAgeSeconds: 60 * 60 * 24 * 7 // 7 days
|
||||||
|
},
|
||||||
|
cacheableResponse: {
|
||||||
|
statuses: [0, 200]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
urlPattern: /^https:\/\/cards\.scryfall\.io\/.*/i,
|
||||||
|
handler: 'CacheFirst',
|
||||||
|
options: {
|
||||||
|
cacheName: 'card-images-cache',
|
||||||
|
expiration: {
|
||||||
|
maxEntries: 1000,
|
||||||
|
maxAgeSeconds: 60 * 60 * 24 * 30 // 30 days
|
||||||
|
},
|
||||||
|
cacheableResponse: {
|
||||||
|
statuses: [0, 200]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
devOptions: {
|
||||||
|
enabled: true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
],
|
||||||
optimizeDeps: {
|
optimizeDeps: {
|
||||||
exclude: ['lucide-react'],
|
exclude: ['lucide-react'],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user