Refactor code structure and remove redundant changes

This commit is contained in:
pacnpal
2025-11-09 16:31:34 -05:00
parent 2884bc23ce
commit eb68cf40c6
1080 changed files with 27361 additions and 56687 deletions

View File

@@ -0,0 +1,80 @@
/**
* LazyImage Component
* Implements lazy loading for images using Intersection Observer
* Only loads images when they're scrolled into view
*/
import { useState, useEffect, useRef } from 'react';
interface LazyImageProps {
src: string;
alt: string;
className?: string;
onLoad?: () => void;
onError?: (e: React.SyntheticEvent<HTMLImageElement, Event>) => void;
}
export function LazyImage({
src,
alt,
className = '',
onLoad,
onError
}: LazyImageProps) {
const [isLoaded, setIsLoaded] = useState(false);
const [isInView, setIsInView] = useState(false);
const [hasError, setHasError] = useState(false);
const imgRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!imgRef.current) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsInView(true);
observer.disconnect();
}
},
{
rootMargin: '100px', // Start loading 100px before visible
threshold: 0.01,
}
);
observer.observe(imgRef.current);
return () => observer.disconnect();
}, []);
const handleLoad = () => {
setIsLoaded(true);
onLoad?.();
};
const handleError = (e: React.SyntheticEvent<HTMLImageElement, Event>) => {
setHasError(true);
onError?.(e);
};
return (
<div ref={imgRef} className={`relative ${className}`}>
{!isInView || hasError ? (
// Loading skeleton or error state
<div className="w-full h-full bg-muted animate-pulse rounded" />
) : (
<img
src={src}
alt={alt}
onLoad={handleLoad}
onError={handleError}
className={`w-full h-full object-cover transition-opacity duration-300 ${
isLoaded ? 'opacity-100' : 'opacity-0'
}`}
/>
)}
</div>
);
}
LazyImage.displayName = 'LazyImage';

View File

@@ -0,0 +1,114 @@
import { ReactNode } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent } from '@/components/ui/card';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Loader2, AlertCircle } from 'lucide-react';
interface LoadingGateProps {
/** Whether data is still loading */
isLoading: boolean;
/** Optional error to display */
error?: Error | null;
/** Content to render when loaded */
children: ReactNode;
/** Loading variant */
variant?: 'skeleton' | 'spinner' | 'card';
/** Number of skeleton items (for skeleton variant) */
skeletonCount?: number;
/** Custom loading message */
loadingMessage?: string;
/** Custom error message */
errorMessage?: string;
}
/**
* Reusable loading and error state wrapper
*
* Handles common loading patterns:
* - Skeleton loaders
* - Spinner with message
* - Card-based loading states
* - Error display
*
* @example
* ```tsx
* <LoadingGate isLoading={loading} error={error} variant="skeleton" skeletonCount={3}>
* <YourContent />
* </LoadingGate>
* ```
*/
export function LoadingGate({
isLoading,
error,
children,
variant = 'skeleton',
skeletonCount = 3,
loadingMessage = 'Loading...',
errorMessage,
}: LoadingGateProps) {
// Error state
if (error) {
return (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>
{errorMessage || error.message || 'An unexpected error occurred'}
</AlertDescription>
</Alert>
);
}
// Loading state
if (isLoading) {
switch (variant) {
case 'spinner':
return (
<div className="flex flex-col items-center justify-center py-12 gap-4">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">{loadingMessage}</p>
</div>
);
case 'card':
return (
<Card>
<CardContent className="p-6 space-y-3">
{Array.from({ length: skeletonCount }).map((_, i) => (
<div key={i} className="flex items-center gap-4 p-3 border rounded-lg">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-2/3" />
<Skeleton className="h-3 w-1/2" />
</div>
<Skeleton className="h-8 w-24" />
</div>
))}
</CardContent>
</Card>
);
case 'skeleton':
default:
return (
<div className="space-y-3">
{Array.from({ length: skeletonCount }).map((_, i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-3 w-1/2" />
</div>
))}
</div>
);
}
}
// Loaded state
return <>{children}</>;
}

View File

@@ -0,0 +1,87 @@
import { Button } from '@/components/ui/button';
import { ChevronLeft, ChevronRight } from 'lucide-react';
interface PaginationProps {
currentPage: number;
totalPages: number;
onPageChange: (page: number) => void;
isLoading?: boolean;
}
export function Pagination({ currentPage, totalPages, onPageChange, isLoading }: PaginationProps) {
const getPageNumbers = () => {
const pages: (number | string)[] = [];
const showPages = 5;
if (totalPages <= showPages) {
for (let i = 1; i <= totalPages; i++) {
pages.push(i);
}
} else {
if (currentPage <= 3) {
for (let i = 1; i <= 4; i++) pages.push(i);
pages.push('...');
pages.push(totalPages);
} else if (currentPage >= totalPages - 2) {
pages.push(1);
pages.push('...');
for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
} else {
pages.push(1);
pages.push('...');
for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i);
pages.push('...');
pages.push(totalPages);
}
}
return pages;
};
if (totalPages <= 1) return null;
return (
<div className="flex items-center justify-center gap-2 mt-8">
<Button
variant="outline"
size="sm"
onClick={() => onPageChange(currentPage - 1)}
disabled={currentPage === 1 || isLoading}
>
<ChevronLeft className="w-4 h-4" />
Previous
</Button>
<div className="flex items-center gap-1">
{getPageNumbers().map((page, idx) => (
typeof page === 'number' ? (
<Button
key={idx}
variant={currentPage === page ? 'default' : 'outline'}
size="sm"
onClick={() => onPageChange(page)}
disabled={isLoading}
className="min-w-[40px]"
>
{page}
</Button>
) : (
<span key={idx} className="px-2 text-muted-foreground">
{page}
</span>
)
))}
</div>
<Button
variant="outline"
size="sm"
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage === totalPages || isLoading}
>
Next
<ChevronRight className="w-4 h-4" />
</Button>
</div>
);
}

View File

@@ -0,0 +1,90 @@
/**
* PhotoGrid Component
* Reusable photo grid display with modal support
*/
import { memo } from 'react';
import { Eye, AlertCircle } from 'lucide-react';
import { useIsMobile } from '@/hooks/use-mobile';
import type { PhotoItem } from '@/types/photos';
import { generatePhotoAlt } from '@/lib/photoHelpers';
import { LazyImage } from '@/components/common/LazyImage';
interface PhotoGridProps {
photos: PhotoItem[];
onPhotoClick?: (photos: PhotoItem[], index: number) => void;
maxDisplay?: number;
className?: string;
}
export const PhotoGrid = memo(({
photos,
onPhotoClick,
maxDisplay,
className = ''
}: PhotoGridProps) => {
const isMobile = useIsMobile();
const defaultMaxDisplay = isMobile ? 2 : 3;
const maxToShow = maxDisplay ?? defaultMaxDisplay;
const displayPhotos = photos.slice(0, maxToShow);
const remainingCount = Math.max(0, photos.length - maxToShow);
if (photos.length === 0) {
return (
<div className="text-sm text-muted-foreground flex items-center gap-2">
<AlertCircle className="w-4 h-4" />
No photos available
</div>
);
}
return (
<div className={`grid gap-2 ${isMobile ? 'grid-cols-2' : 'grid-cols-3'} ${className}`}>
{displayPhotos.map((photo, index) => (
<div
key={photo.id}
className="relative cursor-pointer group overflow-hidden rounded-md border bg-muted/30 h-32"
onClick={() => onPhotoClick?.(photos, index)}
>
<LazyImage
src={photo.url}
alt={generatePhotoAlt(photo)}
className="w-full h-32"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
const parent = target.parentElement;
if (parent) {
const errorDiv = document.createElement('div');
errorDiv.className = 'absolute inset-0 flex flex-col items-center justify-center text-destructive text-xs p-2';
const icon = document.createElement('div');
icon.textContent = '⚠️';
icon.className = 'text-lg mb-1';
const text = document.createElement('div');
text.textContent = 'Failed to load';
errorDiv.appendChild(icon);
errorDiv.appendChild(text);
parent.appendChild(errorDiv);
}
}}
/>
<div className="absolute inset-0 flex items-center justify-center bg-black/50 text-white opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
<Eye className="w-5 h-5" />
</div>
{photo.caption && (
<div className="absolute bottom-0 left-0 right-0 bg-black/70 text-white text-xs p-1 truncate">
{photo.caption}
</div>
)}
</div>
))}
{remainingCount > 0 && (
<div className="flex items-center justify-center bg-muted rounded-md text-sm text-muted-foreground font-medium">
+{remainingCount} more
</div>
)}
</div>
);
});
PhotoGrid.displayName = 'PhotoGrid';

View File

@@ -0,0 +1,156 @@
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { User, Shield, ShieldCheck, Crown } from 'lucide-react';
import { getRoleLabel } from '@/lib/moderation/constants';
interface ProfileBadgeProps {
/** Username to display */
username?: string;
/** Display name (fallback to username) */
displayName?: string;
/** Avatar image URL */
avatarUrl?: string;
/** User role */
role?: 'admin' | 'moderator' | 'user' | 'superuser';
/** Show role badge */
showRole?: boolean;
/** Size variant */
size?: 'sm' | 'md' | 'lg';
/** Whether to show as a link */
clickable?: boolean;
/** Custom click handler */
onClick?: () => void;
}
const sizeClasses = {
sm: {
avatar: 'h-6 w-6',
text: 'text-xs',
badge: 'h-4 text-[10px] px-1',
},
md: {
avatar: 'h-8 w-8',
text: 'text-sm',
badge: 'h-5 text-xs px-1.5',
},
lg: {
avatar: 'h-10 w-10',
text: 'text-base',
badge: 'h-6 text-sm px-2',
},
};
const roleIcons = {
superuser: Crown,
admin: ShieldCheck,
moderator: Shield,
user: User,
};
const roleColors = {
superuser: 'bg-purple-500/10 text-purple-700 dark:text-purple-400 border-purple-500/20',
admin: 'bg-red-500/10 text-red-700 dark:text-red-400 border-red-500/20',
moderator: 'bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-500/20',
user: 'bg-muted text-muted-foreground border-border',
};
/**
* Reusable user profile badge component
*
* Displays user avatar, name, and optional role badge
* Used consistently across moderation queue and admin panels
*
* @example
* ```tsx
* <ProfileBadge
* username="johndoe"
* displayName="John Doe"
* avatarUrl="/avatars/john.jpg"
* role="moderator"
* showRole
* size="md"
* />
* ```
*/
export function ProfileBadge({
username,
displayName,
avatarUrl,
role = 'user',
showRole = false,
size = 'md',
clickable = false,
onClick,
}: ProfileBadgeProps) {
const sizes = sizeClasses[size];
const name = displayName || username || 'Anonymous';
const initials = name
.split(' ')
.map(n => n[0])
.join('')
.toUpperCase()
.slice(0, 2);
const RoleIcon = roleIcons[role];
const content = (
<div
className={`flex items-center gap-2 ${clickable ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
onClick={onClick}
>
<Avatar className={sizes.avatar}>
<AvatarImage src={avatarUrl} alt={name} />
<AvatarFallback className="text-[10px]">{initials}</AvatarFallback>
</Avatar>
<div className="flex flex-col min-w-0">
<span className={`font-medium truncate ${sizes.text}`}>
{name}
</span>
{username && displayName && (
<span className="text-xs text-muted-foreground truncate">
@{username}
</span>
)}
</div>
{showRole && role !== 'user' && (
<Badge
variant="outline"
className={`${sizes.badge} ${roleColors[role]} flex items-center gap-1`}
>
<RoleIcon className="h-3 w-3" />
<span className="hidden sm:inline">{getRoleLabel(role)}</span>
</Badge>
)}
</div>
);
if (showRole && role !== 'user') {
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
{content}
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">
{getRoleLabel(role)}
{username && ` • @${username}`}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
return content;
}

View File

@@ -0,0 +1,122 @@
import { ArrowUp, ArrowDown, Loader2 } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
interface SortControlsProps<T extends string = string> {
/** Current sort field */
sortField: T;
/** Current sort direction */
sortDirection: 'asc' | 'desc';
/** Available sort fields with labels */
sortFields: Record<T, string>;
/** Handler for field change */
onFieldChange: (field: T) => void;
/** Handler for direction toggle */
onDirectionToggle: () => void;
/** Whether component is in mobile mode */
isMobile?: boolean;
/** Whether data is loading */
isLoading?: boolean;
/** Optional label for the sort selector */
label?: string;
}
/**
* Generic reusable sort controls component
*
* Provides consistent sorting UI across the application:
* - Field selector with custom labels
* - Direction toggle (asc/desc)
* - Mobile-responsive layout
* - Loading states
*
* @example
* ```tsx
* <SortControls
* sortField={sortConfig.field}
* sortDirection={sortConfig.direction}
* sortFields={{
* created_at: 'Date Created',
* name: 'Name',
* status: 'Status'
* }}
* onFieldChange={(field) => setSortConfig({ ...sortConfig, field })}
* onDirectionToggle={() => setSortConfig({
* ...sortConfig,
* direction: sortConfig.direction === 'asc' ? 'desc' : 'asc'
* })}
* isMobile={isMobile}
* />
* ```
*/
export function SortControls<T extends string = string>({
sortField,
sortDirection,
sortFields,
onFieldChange,
onDirectionToggle,
isMobile = false,
isLoading = false,
label = 'Sort By',
}: SortControlsProps<T>) {
const DirectionIcon = sortDirection === 'asc' ? ArrowUp : ArrowDown;
return (
<div className={`flex gap-2 ${isMobile ? 'flex-col' : 'items-end'}`}>
<div className={`space-y-2 ${isMobile ? 'w-full' : 'min-w-[160px]'}`}>
<Label className={`font-medium ${isMobile ? 'text-xs' : 'text-sm'} flex items-center gap-2`}>
{label}
{isLoading && <Loader2 className="w-3 h-3 animate-spin text-primary" />}
</Label>
<Select
value={sortField}
onValueChange={onFieldChange}
disabled={isLoading}
>
<SelectTrigger className={isMobile ? "h-10" : ""} disabled={isLoading}>
<SelectValue>
{sortFields[sortField]}
</SelectValue>
</SelectTrigger>
<SelectContent>
{Object.entries(sortFields).map(([field, label]) => (
<SelectItem key={field} value={field}>
{label as string}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className={isMobile ? "" : "pb-[2px]"}>
<Button
variant="outline"
size={isMobile ? "default" : "icon"}
onClick={onDirectionToggle}
disabled={isLoading}
className={`flex items-center gap-2 ${isMobile ? 'w-full h-10' : 'h-10 w-10'}`}
title={sortDirection === 'asc' ? 'Ascending' : 'Descending'}
>
{isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<DirectionIcon className="w-4 h-4" />
)}
{isMobile && (
<span className="capitalize">
{isLoading ? 'Loading...' : `${sortDirection}ending`}
</span>
)}
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,4 @@
// Common reusable components barrel exports
export { LoadingGate } from './LoadingGate';
export { ProfileBadge } from './ProfileBadge';
export { SortControls } from './SortControls';