4 Commits

4 changed files with 389 additions and 27 deletions

View File

@@ -1,17 +1,25 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Search, Loader2, Trash2, CheckCircle, XCircle, RefreshCw, Plus, Minus, X } from 'lucide-react';
import { Card } from '../types';
import { getUserCollection, getCardsByIds, addCardToCollection } from '../services/api';
import { getUserCollectionPaginated, getCardsByIds, addCardToCollection, getCollectionTotalValue } from '../services/api';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase';
import ConfirmModal from './ConfirmModal';
const PAGE_SIZE = 50;
export default function Collection() {
const { user } = useAuth();
const [searchQuery, setSearchQuery] = useState('');
const [collection, setCollection] = useState<{ card: Card; quantity: number }[]>([]);
const [filteredCollection, setFilteredCollection] = useState<{ card: Card; quantity: number }[]>([]);
const [isLoadingCollection, setIsLoadingCollection] = useState(true);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const [hasMore, setHasMore] = useState(false);
const [offset, setOffset] = useState(0);
const [totalCount, setTotalCount] = useState(0);
const [totalCollectionValue, setTotalCollectionValue] = useState<number>(0);
const [isLoadingTotalValue, setIsLoadingTotalValue] = 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());
@@ -22,6 +30,7 @@ export default function Collection() {
cardId: string;
cardName: string;
}>({ isOpen: false, cardId: '', cardName: '' });
const observerTarget = useRef<HTMLDivElement>(null);
// Helper function to check if a card has an actual back face (not adventure/split/etc)
const isDoubleFaced = (card: Card) => {
@@ -62,6 +71,30 @@ export default function Collection() {
});
};
// Calculate total collection value (lightweight query from database)
useEffect(() => {
const calculateTotalValue = async () => {
if (!user) {
setIsLoadingTotalValue(false);
return;
}
try {
setIsLoadingTotalValue(true);
// Get total value directly from database (no need to fetch all cards!)
const totalValue = await getCollectionTotalValue(user.id);
setTotalCollectionValue(totalValue);
} catch (error) {
console.error('Error calculating total collection value:', error);
setTotalCollectionValue(0);
} finally {
setIsLoadingTotalValue(false);
}
};
calculateTotalValue();
}, [user]);
// Load user's collection from Supabase on mount
useEffect(() => {
const loadCollection = async () => {
@@ -72,26 +105,33 @@ export default function Collection() {
try {
setIsLoadingCollection(true);
// Get collection from Supabase (returns Map<card_id, quantity>)
const collectionMap = await getUserCollection(user.id);
setOffset(0);
setCollection([]);
if (collectionMap.size === 0) {
// Get paginated collection from Supabase
const result = await getUserCollectionPaginated(user.id, PAGE_SIZE, 0);
setTotalCount(result.totalCount);
setHasMore(result.hasMore);
if (result.items.size === 0) {
setCollection([]);
setFilteredCollection([]);
return;
}
// Get the actual card data from Scryfall for all cards in collection
const cardIds = Array.from(collectionMap.keys());
// Get the actual card data from Scryfall for all cards in this page
const cardIds = Array.from(result.items.keys());
const cards = await getCardsByIds(cardIds);
// Combine card data with quantities
const collectionWithCards = cards.map(card => ({
card,
quantity: collectionMap.get(card.id) || 0,
quantity: result.items.get(card.id) || 0,
}));
setCollection(collectionWithCards);
setFilteredCollection(collectionWithCards);
setOffset(PAGE_SIZE);
} catch (error) {
console.error('Error loading collection:', error);
setSnackbar({ message: 'Failed to load collection', type: 'error' });
@@ -103,6 +143,64 @@ export default function Collection() {
loadCollection();
}, [user]);
// Load more cards for infinite scroll
const loadMoreCards = useCallback(async () => {
if (!user || isLoadingMore || !hasMore) return;
try {
setIsLoadingMore(true);
// Get next page of collection
const result = await getUserCollectionPaginated(user.id, PAGE_SIZE, offset);
setHasMore(result.hasMore);
if (result.items.size === 0) {
return;
}
// Get card data from Scryfall
const cardIds = Array.from(result.items.keys());
const cards = await getCardsByIds(cardIds);
// Combine card data with quantities
const newCards = cards.map(card => ({
card,
quantity: result.items.get(card.id) || 0,
}));
setCollection(prev => [...prev, ...newCards]);
setOffset(prev => prev + PAGE_SIZE);
} catch (error) {
console.error('Error loading more cards:', error);
setSnackbar({ message: 'Failed to load more cards', type: 'error' });
} finally {
setIsLoadingMore(false);
}
}, [user, offset, hasMore, isLoadingMore]);
// Intersection Observer for infinite scroll
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore && !isLoadingMore) {
loadMoreCards();
}
},
{ threshold: 0.1 }
);
const currentTarget = observerTarget.current;
if (currentTarget) {
observer.observe(currentTarget);
}
return () => {
if (currentTarget) {
observer.unobserve(currentTarget);
}
};
}, [hasMore, isLoadingMore, loadMoreCards]);
// Filter collection based on search query
useEffect(() => {
if (!searchQuery.trim()) {
@@ -209,9 +307,31 @@ export default function Collection() {
{/* Collection */}
<div>
<h2 className="text-xl font-semibold mb-4">
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`}
</h2>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
<h2 className="text-xl font-semibold">
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`}
</h2>
{/* Collection Value Summary */}
<div className="bg-gray-800 border border-gray-700 rounded-lg px-4 py-2">
<div className="text-xs text-gray-400 mb-0.5">
{searchQuery ? 'Filtered Value' : 'Total Collection Value'}
</div>
<div className="text-lg font-bold text-green-400">
{isLoadingTotalValue ? (
<Loader2 className="animate-spin" size={20} />
) : searchQuery ? (
// For search results, calculate from filtered collection
`$${filteredCollection.reduce((total, { card, quantity }) => {
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
return total + (price * quantity);
}, 0).toFixed(2)}`
) : (
// For full collection, use pre-calculated total
`$${totalCollectionValue.toFixed(2)}`
)}
</div>
</div>
</div>
{isLoadingCollection ? (
<div className="flex items-center justify-center py-12">
@@ -255,6 +375,12 @@ export default function Collection() {
<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>
{/* Price badge */}
{card.prices?.usd && (
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-[10px] sm:text-xs font-bold px-1.5 py-0.5 rounded shadow-lg">
${card.prices.usd}
</div>
)}
{/* Flip button for double-faced cards */}
{isMultiFaced && (
<button
@@ -279,6 +405,25 @@ export default function Collection() {
})}
</div>
)}
{/* Infinite scroll loading indicator */}
{!searchQuery && isLoadingMore && (
<div className="flex justify-center py-8">
<Loader2 className="animate-spin text-blue-500" size={32} />
</div>
)}
{/* Observer target for infinite scroll */}
{!searchQuery && hasMore && !isLoadingMore && (
<div ref={observerTarget} className="h-20" />
)}
{/* End of collection indicator */}
{!searchQuery && !hasMore && collection.length > 0 && (
<div className="text-center py-8 text-gray-500 text-sm">
End of collection {totalCount} total cards
</div>
)}
</div>
</div>

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save, ChevronLeft, RefreshCw, Plus, Minus } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { useToast } from '../contexts/ToastContext';
@@ -23,7 +23,7 @@ import {
Trade,
TradeItem,
} from '../services/tradesService';
import { getUserCollection, getCardsByIds } from '../services/api';
import { getUserCollectionPaginated, getCardsByIds, getCollectionTotalValue } from '../services/api';
import { Card } from '../types';
import TradeCreator from './TradeCreator';
import TradeDetail from './TradeDetail';
@@ -50,6 +50,8 @@ const VISIBILITY_OPTIONS = [
{ value: 'private', label: 'Private', description: 'Only you' },
] as const;
const PAGE_SIZE = 50;
export default function Community() {
const { user } = useAuth();
const toast = useToast();
@@ -62,11 +64,18 @@ export default function Community() {
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
const [loadingCollection, setLoadingCollection] = useState(false);
const [isLoadingMoreUserCards, setIsLoadingMoreUserCards] = useState(false);
const [hasMoreUserCards, setHasMoreUserCards] = useState(false);
const [userCollectionOffset, setUserCollectionOffset] = useState(0);
const [userCollectionTotalCount, setUserCollectionTotalCount] = useState(0);
const [userCollectionTotalValue, setUserCollectionTotalValue] = useState<number>(0);
const [isLoadingUserTotalValue, setIsLoadingUserTotalValue] = useState(true);
const [showTradeCreator, setShowTradeCreator] = useState(false);
const [userCollectionSearch, setUserCollectionSearch] = useState('');
const [hoveredUserCard, setHoveredUserCard] = useState<Card | null>(null);
const [selectedUserCard, setSelectedUserCard] = useState<CollectionItem | null>(null);
const [userCardFaceIndex, setUserCardFaceIndex] = useState<Map<string, number>>(new Map());
const userCollectionObserverTarget = useRef<HTMLDivElement>(null);
// Friends state
const [friendsSubTab, setFriendsSubTab] = useState<FriendsSubTab>('list');
@@ -298,26 +307,104 @@ export default function Community() {
const loadUserCollection = async (userId: string) => {
setLoadingCollection(true);
setIsLoadingUserTotalValue(true);
setSelectedUserCollection([]);
setUserCollectionOffset(0);
try {
const collectionMap = await getUserCollection(userId);
if (collectionMap.size === 0) {
// Load paginated collection for display
const result = await getUserCollectionPaginated(userId, PAGE_SIZE, 0);
setUserCollectionTotalCount(result.totalCount);
setHasMoreUserCards(result.hasMore);
if (result.items.size === 0) {
setSelectedUserCollection([]);
setUserCollectionTotalValue(0);
setIsLoadingUserTotalValue(false);
return;
}
const cardIds = Array.from(collectionMap.keys());
const cardIds = Array.from(result.items.keys());
const cards = await getCardsByIds(cardIds);
setSelectedUserCollection(cards.map((card) => ({
card,
quantity: collectionMap.get(card.id) || 0,
quantity: result.items.get(card.id) || 0,
})));
setUserCollectionOffset(PAGE_SIZE);
// Calculate total value (lightweight query from database)
const totalValue = await getCollectionTotalValue(userId);
setUserCollectionTotalValue(totalValue);
} catch (error) {
console.error('Error loading collection:', error);
setSelectedUserCollection([]);
setUserCollectionTotalValue(0);
} finally {
setLoadingCollection(false);
setIsLoadingUserTotalValue(false);
}
};
// Load more cards for infinite scroll in user collection view
const loadMoreUserCards = useCallback(async () => {
if (!selectedUser || isLoadingMoreUserCards || !hasMoreUserCards) return;
try {
setIsLoadingMoreUserCards(true);
const result = await getUserCollectionPaginated(
selectedUser.id,
PAGE_SIZE,
userCollectionOffset
);
setHasMoreUserCards(result.hasMore);
if (result.items.size === 0) {
return;
}
const cardIds = Array.from(result.items.keys());
const cards = await getCardsByIds(cardIds);
const newCards = cards.map(card => ({
card,
quantity: result.items.get(card.id) || 0,
}));
setSelectedUserCollection(prev => [...prev, ...newCards]);
setUserCollectionOffset(prev => prev + PAGE_SIZE);
} catch (error) {
console.error('Error loading more cards:', error);
} finally {
setIsLoadingMoreUserCards(false);
}
}, [selectedUser, userCollectionOffset, hasMoreUserCards, isLoadingMoreUserCards]);
// Intersection Observer for infinite scroll in user collection view
useEffect(() => {
if (!selectedUser) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMoreUserCards && !isLoadingMoreUserCards) {
loadMoreUserCards();
}
},
{ threshold: 0.1 }
);
const currentTarget = userCollectionObserverTarget.current;
if (currentTarget) {
observer.observe(currentTarget);
}
return () => {
if (currentTarget) {
observer.unobserve(currentTarget);
}
};
}, [selectedUser, hasMoreUserCards, isLoadingMoreUserCards, loadMoreUserCards]);
// ============ FRIENDS FUNCTIONS ============
const loadFriendsData = async () => {
if (!user) return;
@@ -617,12 +704,34 @@ export default function Community() {
{/* Collection */}
<div>
<h2 className="text-xl font-semibold mb-4">
{userCollectionSearch
? `Found ${filteredUserCollection.length} card(s)`
: `Cards (${selectedUserCollection.length} unique, ${selectedUserCollection.reduce((acc, c) => acc + c.quantity, 0)} total)`
}
</h2>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
<h2 className="text-xl font-semibold">
{userCollectionSearch
? `Found ${filteredUserCollection.length} card(s)`
: `Cards (${selectedUserCollection.length} unique, ${selectedUserCollection.reduce((acc, c) => acc + c.quantity, 0)} total)`
}
</h2>
{/* Collection Value Summary */}
<div className="bg-gray-800 border border-gray-700 rounded-lg px-4 py-2">
<div className="text-xs text-gray-400 mb-0.5">
{userCollectionSearch ? 'Filtered Value' : 'Total Collection Value'}
</div>
<div className="text-lg font-bold text-green-400">
{isLoadingUserTotalValue ? (
<Loader2 className="animate-spin" size={20} />
) : userCollectionSearch ? (
// For search results, calculate from filtered collection
`$${filteredUserCollection.reduce((total, { card, quantity }) => {
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
return total + (price * quantity);
}, 0).toFixed(2)}`
) : (
// For full collection, use pre-calculated total
`$${userCollectionTotalValue.toFixed(2)}`
)}
</div>
</div>
</div>
{loadingCollection ? (
<div className="flex items-center justify-center py-12">
@@ -665,6 +774,12 @@ export default function Community() {
<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>
{/* Price badge */}
{card.prices?.usd && (
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-[10px] sm:text-xs font-bold px-1.5 py-0.5 rounded shadow-lg">
${card.prices.usd}
</div>
)}
{/* Flip button for double-faced cards */}
{isMultiFaced && (
<button
@@ -689,6 +804,25 @@ export default function Community() {
})}
</div>
)}
{/* Infinite scroll loading indicator */}
{!userCollectionSearch && isLoadingMoreUserCards && (
<div className="flex justify-center py-8">
<Loader2 className="animate-spin text-blue-500" size={32} />
</div>
)}
{/* Observer target for infinite scroll */}
{!userCollectionSearch && hasMoreUserCards && !isLoadingMoreUserCards && (
<div ref={userCollectionObserverTarget} className="h-20" />
)}
{/* End of collection indicator */}
{!userCollectionSearch && !hasMoreUserCards && selectedUserCollection.length > 0 && (
<div className="text-center py-8 text-gray-500 text-sm">
End of collection • {userCollectionTotalCount} total cards
</div>
)}
</div>
</div>

View File

@@ -75,10 +75,76 @@ export const getUserCollection = async (userId: string): Promise<Map<string, num
return collectionMap;
};
// Paginated collection API
export interface PaginatedCollectionResult {
items: Map<string, number>; // card_id -> quantity
totalCount: number;
hasMore: boolean;
}
// Get total collection value from user profile (pre-calculated by triggers)
export const getCollectionTotalValue = async (userId: string): Promise<number> => {
const { data, error } = await supabase
.from('profiles')
.select('collection_total_value')
.eq('id', userId)
.single();
if (error) {
console.error('Error fetching collection total value:', error);
return 0;
}
return data?.collection_total_value || 0;
};
export const getUserCollectionPaginated = async (
userId: string,
pageSize: number = 50,
offset: number = 0
): Promise<PaginatedCollectionResult> => {
// First, get the total count
const { count: totalCount, error: countError } = await supabase
.from('collections')
.select('*', { count: 'exact', head: true })
.eq('user_id', userId);
if (countError) {
console.error('Error counting user collection:', countError);
throw countError;
}
// Then get the paginated data
const { data, error } = await supabase
.from('collections')
.select('card_id, quantity')
.eq('user_id', userId)
.order('created_at', { ascending: false })
.range(offset, offset + pageSize - 1);
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 {
items: collectionMap,
totalCount: totalCount || 0,
hasMore: offset + pageSize < (totalCount || 0),
};
};
export const addCardToCollection = async (
userId: string,
cardId: string,
quantity: number = 1
quantity: number = 1,
priceUsd: number = 0
): Promise<void> => {
// Check if card already exists in collection
const { data: existing, error: fetchError } = await supabase
@@ -94,11 +160,12 @@ export const addCardToCollection = async (
}
if (existing) {
// Update existing card quantity
// Update existing card quantity and price
const { error: updateError } = await supabase
.from('collections')
.update({
quantity: existing.quantity + quantity,
price_usd: priceUsd,
updated_at: new Date().toISOString()
})
.eq('id', existing.id);
@@ -112,6 +179,7 @@ export const addCardToCollection = async (
user_id: userId,
card_id: cardId,
quantity: quantity,
price_usd: priceUsd,
});
if (insertError) throw insertError;
@@ -120,7 +188,7 @@ export const addCardToCollection = async (
export const addMultipleCardsToCollection = async (
userId: string,
cards: { cardId: string; quantity: number }[]
cards: { cardId: string; quantity: number; priceUsd?: number }[]
): Promise<void> => {
// Fetch existing cards in collection
const cardIds = cards.map(c => c.cardId);
@@ -146,6 +214,7 @@ export const addMultipleCardsToCollection = async (
toUpdate.push({
id: existing.id,
quantity: existing.quantity + card.quantity,
price_usd: card.priceUsd || 0,
updated_at: new Date().toISOString(),
});
} else {
@@ -153,6 +222,7 @@ export const addMultipleCardsToCollection = async (
user_id: userId,
card_id: card.cardId,
quantity: card.quantity,
price_usd: card.priceUsd || 0,
});
}
}
@@ -170,7 +240,11 @@ export const addMultipleCardsToCollection = async (
for (const update of toUpdate) {
const { error: updateError } = await supabase
.from('collections')
.update({ quantity: update.quantity, updated_at: update.updated_at })
.update({
quantity: update.quantity,
price_usd: update.price_usd,
updated_at: update.updated_at
})
.eq('id', update.id);
if (updateError) throw updateError;

View File

@@ -0,0 +1,9 @@
-- Add price_usd column to collections table
ALTER TABLE collections
ADD COLUMN IF NOT EXISTS price_usd DECIMAL(10, 2) DEFAULT 0;
-- Create index for faster price calculations
CREATE INDEX IF NOT EXISTS idx_collections_price ON collections(price_usd);
-- Add comment
COMMENT ON COLUMN collections.price_usd IS 'USD price of the card at time of addition/update';