implement paginated user collection API and infinite scroll in collection views

This commit is contained in:
Matthieu
2025-11-27 11:47:19 +01:00
parent 71891a29be
commit 359cc61115
3 changed files with 292 additions and 23 deletions

View File

@@ -1,17 +1,23 @@
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 { Search, Loader2, Trash2, CheckCircle, XCircle, RefreshCw, Plus, Minus, X } from 'lucide-react';
import { Card } from '../types'; import { Card } from '../types';
import { getUserCollection, getCardsByIds, addCardToCollection } from '../services/api'; import { getUserCollectionPaginated, getCardsByIds, addCardToCollection } from '../services/api';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase'; import { supabase } from '../lib/supabase';
import ConfirmModal from './ConfirmModal'; import ConfirmModal from './ConfirmModal';
const PAGE_SIZE = 50;
export default function Collection() { export default function Collection() {
const { user } = useAuth(); const { user } = useAuth();
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
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 [filteredCollection, setFilteredCollection] = useState<{ card: Card; quantity: number }[]>([]);
const [isLoadingCollection, setIsLoadingCollection] = useState(true); 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 [hoveredCard, setHoveredCard] = useState<Card | null>(null); const [hoveredCard, setHoveredCard] = useState<Card | null>(null);
const [selectedCard, setSelectedCard] = useState<{ card: Card; quantity: number } | null>(null); const [selectedCard, setSelectedCard] = useState<{ card: Card; quantity: number } | null>(null);
const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map()); const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map());
@@ -22,6 +28,7 @@ export default function Collection() {
cardId: string; cardId: string;
cardName: string; cardName: string;
}>({ isOpen: false, cardId: '', cardName: '' }); }>({ 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) // Helper function to check if a card has an actual back face (not adventure/split/etc)
const isDoubleFaced = (card: Card) => { const isDoubleFaced = (card: Card) => {
@@ -72,26 +79,33 @@ export default function Collection() {
try { try {
setIsLoadingCollection(true); setIsLoadingCollection(true);
// Get collection from Supabase (returns Map<card_id, quantity>) setOffset(0);
const collectionMap = await getUserCollection(user.id); 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([]); setCollection([]);
setFilteredCollection([]);
return; return;
} }
// Get the actual card data from Scryfall for all cards in collection // Get the actual card data from Scryfall for all cards in this page
const cardIds = Array.from(collectionMap.keys()); const cardIds = Array.from(result.items.keys());
const cards = await getCardsByIds(cardIds); const cards = await getCardsByIds(cardIds);
// Combine card data with quantities // Combine card data with quantities
const collectionWithCards = cards.map(card => ({ const collectionWithCards = cards.map(card => ({
card, card,
quantity: collectionMap.get(card.id) || 0, quantity: result.items.get(card.id) || 0,
})); }));
setCollection(collectionWithCards); setCollection(collectionWithCards);
setFilteredCollection(collectionWithCards); setFilteredCollection(collectionWithCards);
setOffset(PAGE_SIZE);
} catch (error) { } catch (error) {
console.error('Error loading collection:', error); console.error('Error loading collection:', error);
setSnackbar({ message: 'Failed to load collection', type: 'error' }); setSnackbar({ message: 'Failed to load collection', type: 'error' });
@@ -103,6 +117,64 @@ export default function Collection() {
loadCollection(); loadCollection();
}, [user]); }, [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 // Filter collection based on search query
useEffect(() => { useEffect(() => {
if (!searchQuery.trim()) { if (!searchQuery.trim()) {
@@ -209,9 +281,21 @@ export default function Collection() {
{/* Collection */} {/* Collection */}
<div> <div>
<h2 className="text-xl font-semibold mb-4"> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`} <h2 className="text-xl font-semibold">
</h2> {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">Total Collection Value</div>
<div className="text-lg font-bold text-green-400">
${(searchQuery ? filteredCollection : collection).reduce((total, { card, quantity }) => {
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
return total + (price * quantity);
}, 0).toFixed(2)}
</div>
</div>
</div>
{isLoadingCollection ? ( {isLoadingCollection ? (
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
@@ -255,6 +339,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"> <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} x{quantity}
</div> </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 */} {/* Flip button for double-faced cards */}
{isMultiFaced && ( {isMultiFaced && (
<button <button
@@ -279,6 +369,25 @@ export default function Collection() {
})} })}
</div> </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>
</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 { 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 { useAuth } from '../contexts/AuthContext';
import { useToast } from '../contexts/ToastContext'; import { useToast } from '../contexts/ToastContext';
@@ -23,7 +23,7 @@ import {
Trade, Trade,
TradeItem, TradeItem,
} from '../services/tradesService'; } from '../services/tradesService';
import { getUserCollection, getCardsByIds } from '../services/api'; import { getUserCollection, getUserCollectionPaginated, getCardsByIds } from '../services/api';
import { Card } from '../types'; import { Card } from '../types';
import TradeCreator from './TradeCreator'; import TradeCreator from './TradeCreator';
import TradeDetail from './TradeDetail'; import TradeDetail from './TradeDetail';
@@ -50,6 +50,8 @@ const VISIBILITY_OPTIONS = [
{ value: 'private', label: 'Private', description: 'Only you' }, { value: 'private', label: 'Private', description: 'Only you' },
] as const; ] as const;
const PAGE_SIZE = 50;
export default function Community() { export default function Community() {
const { user } = useAuth(); const { user } = useAuth();
const toast = useToast(); const toast = useToast();
@@ -62,11 +64,16 @@ export default function Community() {
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null); const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]); const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
const [loadingCollection, setLoadingCollection] = useState(false); 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 [showTradeCreator, setShowTradeCreator] = useState(false); const [showTradeCreator, setShowTradeCreator] = useState(false);
const [userCollectionSearch, setUserCollectionSearch] = useState(''); const [userCollectionSearch, setUserCollectionSearch] = useState('');
const [hoveredUserCard, setHoveredUserCard] = useState<Card | null>(null); const [hoveredUserCard, setHoveredUserCard] = useState<Card | null>(null);
const [selectedUserCard, setSelectedUserCard] = useState<CollectionItem | null>(null); const [selectedUserCard, setSelectedUserCard] = useState<CollectionItem | null>(null);
const [userCardFaceIndex, setUserCardFaceIndex] = useState<Map<string, number>>(new Map()); const [userCardFaceIndex, setUserCardFaceIndex] = useState<Map<string, number>>(new Map());
const userCollectionObserverTarget = useRef<HTMLDivElement>(null);
// Friends state // Friends state
const [friendsSubTab, setFriendsSubTab] = useState<FriendsSubTab>('list'); const [friendsSubTab, setFriendsSubTab] = useState<FriendsSubTab>('list');
@@ -298,18 +305,25 @@ export default function Community() {
const loadUserCollection = async (userId: string) => { const loadUserCollection = async (userId: string) => {
setLoadingCollection(true); setLoadingCollection(true);
setSelectedUserCollection([]);
setUserCollectionOffset(0);
try { try {
const collectionMap = await getUserCollection(userId); const result = await getUserCollectionPaginated(userId, PAGE_SIZE, 0);
if (collectionMap.size === 0) { setUserCollectionTotalCount(result.totalCount);
setHasMoreUserCards(result.hasMore);
if (result.items.size === 0) {
setSelectedUserCollection([]); setSelectedUserCollection([]);
return; return;
} }
const cardIds = Array.from(collectionMap.keys());
const cardIds = Array.from(result.items.keys());
const cards = await getCardsByIds(cardIds); const cards = await getCardsByIds(cardIds);
setSelectedUserCollection(cards.map((card) => ({ setSelectedUserCollection(cards.map((card) => ({
card, card,
quantity: collectionMap.get(card.id) || 0, quantity: result.items.get(card.id) || 0,
}))); })));
setUserCollectionOffset(PAGE_SIZE);
} catch (error) { } catch (error) {
console.error('Error loading collection:', error); console.error('Error loading collection:', error);
setSelectedUserCollection([]); setSelectedUserCollection([]);
@@ -318,6 +332,66 @@ export default function Community() {
} }
}; };
// 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 ============ // ============ FRIENDS FUNCTIONS ============
const loadFriendsData = async () => { const loadFriendsData = async () => {
if (!user) return; if (!user) return;
@@ -617,12 +691,24 @@ export default function Community() {
{/* Collection */} {/* Collection */}
<div> <div>
<h2 className="text-xl font-semibold mb-4"> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
{userCollectionSearch <h2 className="text-xl font-semibold">
? `Found ${filteredUserCollection.length} card(s)` {userCollectionSearch
: `Cards (${selectedUserCollection.length} unique, ${selectedUserCollection.reduce((acc, c) => acc + c.quantity, 0)} total)` ? `Found ${filteredUserCollection.length} card(s)`
} : `Cards (${selectedUserCollection.length} unique, ${selectedUserCollection.reduce((acc, c) => acc + c.quantity, 0)} total)`
</h2> }
</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">Total Collection Value</div>
<div className="text-lg font-bold text-green-400">
${(userCollectionSearch ? filteredUserCollection : selectedUserCollection).reduce((total, { card, quantity }) => {
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
return total + (price * quantity);
}, 0).toFixed(2)}
</div>
</div>
</div>
{loadingCollection ? ( {loadingCollection ? (
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
@@ -665,6 +751,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"> <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} x{quantity}
</div> </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 */} {/* Flip button for double-faced cards */}
{isMultiFaced && ( {isMultiFaced && (
<button <button
@@ -689,6 +781,25 @@ export default function Community() {
})} })}
</div> </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>
</div> </div>

View File

@@ -75,6 +75,55 @@ export const getUserCollection = async (userId: string): Promise<Map<string, num
return collectionMap; return collectionMap;
}; };
// Paginated collection API
export interface PaginatedCollectionResult {
items: Map<string, number>; // card_id -> quantity
totalCount: number;
hasMore: boolean;
}
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 ( export const addCardToCollection = async (
userId: string, userId: string,
cardId: string, cardId: string,