Initial commit

This commit is contained in:
Rami Bitar
2026-04-19 11:15:55 -04:00
commit eeeafd36d3
78 changed files with 10412 additions and 0 deletions

206
components/CartDrawer.tsx Normal file
View File

@@ -0,0 +1,206 @@
"use client";
import React, { useState } from 'react';
import { RiCloseLine, RiImageLine, RiSubtractLine, RiAddLine, RiLoader4Line } from '@remixicon/react';
import { useShopifyCart, redirectToCheckout } from '@/hooks/use-shopify-cart';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetBody,
SheetFooter,
AnimatePresence,
} from './ui/sheet';
import { Button } from './ui/button';
const CartDrawer: React.FC = () => {
const {
isOpen,
items,
itemCount,
totalAmount,
checkoutUrl,
removeItem,
updateItemQuantity,
closeCart
} = useShopifyCart();
const [isCheckingOut, setIsCheckingOut] = useState(false);
const handleCheckout = async () => {
if (!checkoutUrl) return;
setIsCheckingOut(true);
try {
redirectToCheckout(checkoutUrl);
} catch (error) {
console.error('Error during checkout:', error);
alert('Failed to proceed to checkout. Please try again.');
setIsCheckingOut(false);
}
};
return (
<Sheet open={isOpen} onOpenChange={(open) => !open && closeCart()}>
<AnimatePresence>
{isOpen && (
<SheetContent className="w-full max-w-md" showCloseButton={false}>
{/* Header */}
<SheetHeader className="h-16 justify-center items-start">
<div className="flex items-center justify-between w-full">
<SheetTitle
className="text-2xl font-bold font-heading"
>
Shopping Cart ({itemCount})
</SheetTitle>
<button
onClick={closeCart}
className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
>
<RiCloseLine className="text-sm" />
</button>
</div>
</SheetHeader>
{/* Cart Items */}
<SheetBody>
{items.length === 0 ? (
<div className="text-center py-12">
<h3 className="text-lg font-semibold text-gray-600 mb-2">Your cart is empty</h3>
<p className="text-gray-500 mb-6">Add some products to get started!</p>
<Button onClick={closeCart}>
Continue Shopping
</Button>
</div>
) : (
<div className="space-y-6">
{items.map((item) => (
<div key={item.id} className="flex items-start space-x-4 pb-6 border-b border-gray-200 last:border-b-0">
{/* Product Image */}
<div className="w-20 h-20 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
{item.merchandise.image?.url ? (
<img
src={item.merchandise.image.url}
alt={item.merchandise.image.altText || item.merchandise.product.title}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400">
<RiImageLine className="text-lg" />
</div>
)}
</div>
{/* Product Details */}
<div className="flex-1 min-w-0">
<h4 className="font-semibold text-gray-900 mb-1 line-clamp-2">
{item.merchandise.product.title}
</h4>
{/* Variant Info */}
{item.merchandise.selectedOptions && item.merchandise.selectedOptions.length > 0 && (
<div className="text-sm text-gray-500 mb-2">
{item.merchandise.selectedOptions.map((option, index) => (
<span key={option.name}>
{option.value}
{index < item.merchandise.selectedOptions.length - 1 ? ' / ' : ''}
</span>
))}
</div>
)}
{/* Quantity Controls */}
<div className="flex items-center mt-3">
<div className="flex items-center border border-gray-300 rounded-lg">
<button
onClick={() => updateItemQuantity(item.id, item.quantity - 1)}
className="p-1 hover:bg-gray-100 transition-colors text-gray-500"
disabled={item.quantity <= 1}
>
<RiSubtractLine className="text-xs" />
</button>
<span className="px-2 py-1 font-semibold min-w-[30px] text-center text-sm">
{item.quantity}
</span>
<button
onClick={() => updateItemQuantity(item.id, item.quantity + 1)}
className="p-1 hover:bg-gray-100 transition-colors text-gray-500"
>
<RiAddLine className="text-xs" />
</button>
</div>
</div>
</div>
{/* Price */}
<div className="flex-shrink-0">
<span className="font-semibold text-gray-900">
${parseFloat(item.merchandise.price.amount).toFixed(2)}
</span>
</div>
{/* Remove Button */}
<div className="flex-shrink-0">
<button
onClick={() => removeItem(item.id)}
className="p-1 hover:bg-gray-100 rounded transition-colors text-gray-400 hover:text-red-500"
>
<RiCloseLine className="text-sm" />
</button>
</div>
</div>
))}
</div>
)}
</SheetBody>
{/* Footer - Checkout Section */}
{items.length > 0 && (
<SheetFooter className="!flex-col items-stretch gap-3">
{/* Subtotal */}
<div className="flex items-center justify-between mb-2">
<span className="text-lg font-semibold">Subtotal</span>
<span className="text-lg font-semibold">
${totalAmount.toFixed(2)}
</span>
</div>
<div className="text-sm text-gray-500 mb-2">
Shipping and taxes calculated at checkout
</div>
{/* Action Buttons */}
<Button
onClick={handleCheckout}
disabled={isCheckingOut || !checkoutUrl}
size="lg"
className="w-full"
>
{isCheckingOut ? (
<span className="flex items-center justify-center space-x-2">
<RiLoader4Line className="text-sm animate-spin" />
<span>Processing...</span>
</span>
) : (
'Checkout'
)}
</Button>
<Button
onClick={closeCart}
variant="outline"
size="lg"
className="w-full"
>
Continue Shopping
</Button>
</SheetFooter>
)}
</SheetContent>
)}
</AnimatePresence>
</Sheet>
);
};
export default CartDrawer;

View File

@@ -0,0 +1,64 @@
import React from 'react';
import Link from 'next/link';
interface CollectionImage {
url: string;
altText?: string;
}
interface Collection {
id: string;
title: string;
handle: string;
description?: string;
image?: CollectionImage;
}
interface CollectionCardProps {
collection: Collection;
}
const CollectionCard: React.FC<CollectionCardProps> = ({ collection }) => {
return (
<Link
href={`/collections/${collection.handle}`}
className="bg-white rounded-xs shadow-md hover:shadow-xl transition-shadow duration-300 overflow-hidden group block"
>
{/* Collection Image */}
<div className="aspect-video overflow-hidden bg-gray-100">
{collection.image ? (
<img
src={collection.image.url}
alt={collection.image.altText || collection.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400">
<i className="ri-folder-line text-6xl"></i>
</div>
)}
</div>
{/* Collection Info */}
<div className="p-6">
<h3 className="text-2xl font-bold text-gray-900 mb-3 group-hover:text-gray-600 transition-colors font-heading">
{collection.title}
</h3>
{collection.description && (
<p className="text-gray-600">
{collection.description.substring(0, 100)}
{collection.description.length > 100 ? '...' : ''}
</p>
)}
<div className="mt-4 text-black font-semibold group-hover:text-gray-600 transition-colors flex items-center">
<span>View Collection</span>
<i className="ri-arrow-right-s-line ml-2"></i>
</div>
</div>
</Link>
);
};
export default CollectionCard;

View File

@@ -0,0 +1,180 @@
"use client";
import React, { useState } from 'react';
import { useCollectionProducts } from '@/hooks/use-shopify-collections';
import ProductCard from './ProductCard';
import ProductModal from './ProductModal';
import { Button } from './ui/button';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductPrice {
amount: string;
currencyCode: string;
}
interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
}
interface Product {
id: string;
title: string;
description?: string;
handle: string;
images: {
edges: Array<{
node: ProductImage;
}>;
};
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
variants: {
edges: Array<{
node: ProductVariant;
}>;
};
}
interface CollectionDetailProps {
collectionHandle?: string;
}
const CollectionDetail: React.FC<CollectionDetailProps> = ({ collectionHandle }) => {
const { collection, loading, error } = useCollectionProducts(collectionHandle || null, {
first: 20,
sortKey: 'BEST_SELLING',
reverse: false
});
const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
if (loading) {
return (
<div className="py-16 bg-gray-50">
<div className="container mx-auto px-4">
<h2 className="text-5xl font-bold text-center mb-16 text-gray-900 font-heading">
Collection
</h2>
{/* Loading Skeleton */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{Array.from({ length: 8 }).map((_, index) => (
<div key={index} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
<div className="aspect-square bg-gray-200"></div>
<div className="p-6">
<div className="h-6 bg-gray-200 rounded mb-2"></div>
<div className="h-4 bg-gray-200 rounded mb-4"></div>
<div className="h-8 bg-gray-200 rounded mb-4"></div>
<div className="h-12 bg-gray-200 rounded"></div>
</div>
</div>
))}
</div>
</div>
</div>
);
}
if (error || !collection) {
return (
<div className="container mx-auto px-4 py-24 text-center">
<div className="max-w-lg mx-auto">
<div className="w-20 h-20 mx-auto mb-6 rounded-full bg-gray-100 flex items-center justify-center">
<i className="ri-shopping-bag-line text-3xl text-gray-400"></i>
</div>
<h2 className="text-2xl font-heading font-semibold text-gray-900 mb-3">
Collection Not Found
</h2>
<p className="text-gray-500 mb-8 leading-relaxed">
{error || "We couldn't find the collection you're looking for. It may have been removed or the link might be incorrect."}
</p>
<Button
onClick={() => window.history.back()}
variant="outline"
className="px-8"
>
<i className="ri-arrow-left-line mr-2"></i>
Go Back
</Button>
</div>
</div>
);
}
return (
<div className="bg-gray-50">
{/* Hero Banner */}
{collection.image && (
<div className="relative w-full h-[300px] md:h-[350px] lg:h-[400px]">
<img
src={collection.image.url}
alt={collection.image.altText || collection.title}
className="w-full h-full object-cover object-center"
/>
<div className="absolute inset-0 bg-black/40 flex items-center justify-center">
<h1 className="text-5xl md:text-6xl lg:text-7xl font-bold text-white text-center px-4 font-heading">
{collection.title}
</h1>
</div>
</div>
)}
{/* Products Section */}
<div className="py-16">
<div className="container mx-auto px-4">
{collection.products.length === 0 ? (
<div className="text-center py-12">
<div className="bg-gray-50 border border-gray-200 rounded-lg p-8 max-w-md mx-auto">
<i className="ri-shopping-bag-line text-4xl text-gray-400 mb-4"></i>
<h3 className="text-lg font-semibold text-gray-600 mb-2">
No Products in Collection
</h3>
<p className="text-gray-500">
This collection doesn't have any products yet.
</p>
</div>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{collection.products.map((product) => (
<ProductCard
key={product.id}
product={product}
onClick={(product) => {
setSelectedProduct(product);
setIsModalOpen(true);
}}
/>
))}
</div>
)}
</div>
</div>
{/* Product Modal */}
{selectedProduct && (
<ProductModal
product={selectedProduct}
isOpen={isModalOpen}
onClose={() => {
setIsModalOpen(false);
setSelectedProduct(null);
}}
/>
)}
</div>
);
};
export default CollectionDetail;

105
components/Collections.tsx Normal file
View File

@@ -0,0 +1,105 @@
"use client";
import React from 'react';
import { useCollections } from '@/hooks/use-shopify-collections';
import CollectionCard from './CollectionCard';
import { Button } from './ui/button';
const Collections: React.FC = () => {
const { collections, loading, error, refetch } = useCollections(20);
if (loading) {
return (
<div className="py-16 bg-gray-50">
<div className="max-w-7xl mx-auto px-4">
<h2 className="text-5xl font-bold text-center mb-16 text-gray-900 font-heading">
Our Collections
</h2>
{/* Loading Skeleton */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{Array.from({ length: 6 }).map((_, index) => (
<div key={index} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
<div className="aspect-video bg-gray-200"></div>
<div className="p-6">
<div className="h-8 bg-gray-200 rounded mb-4"></div>
<div className="h-4 bg-gray-200 rounded mb-2"></div>
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
</div>
</div>
))}
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="py-16 bg-gray-50">
<div className="max-w-7xl mx-auto px-4 text-center">
<h2 className="text-5xl font-bold mb-8 font-heading">
Our Collections
</h2>
<div className="bg-red-50 border border-red-200 rounded-lg p-8 max-w-md mx-auto">
<i className="ri-error-warning-line text-4xl text-red-500 mb-4"></i>
<h3 className="text-lg font-semibold text-red-800 mb-2">
Failed to Load Collections
</h3>
<p className="text-red-600 mb-4">
{error}
</p>
<Button
onClick={() => refetch()}
variant="destructive"
>
Try Again
</Button>
</div>
</div>
</div>
);
}
if (collections.length === 0) {
return (
<div className="py-16 bg-gray-50">
<div className="max-w-7xl mx-auto px-4 text-center">
<h2 className="text-5xl font-bold mb-8 font-heading">
Our Collections
</h2>
<div className="bg-gray-50 border border-gray-200 rounded-lg p-8 max-w-md mx-auto">
<i className="ri-folder-line text-4xl text-gray-400 mb-4"></i>
<h3 className="text-lg font-semibold text-gray-600 mb-2">
No Collections Found
</h3>
<p className="text-gray-500">
Check back later or configure your Shopify store connection.
</p>
</div>
</div>
</div>
);
}
return (
<div className="py-16 bg-gray-50">
<div className="max-w-7xl mx-auto px-4">
<h2 className="text-5xl font-bold text-center mb-16 text-gray-900 font-heading">
Our Collections
</h2>
{/* Collections Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{collections.map((collection) => (
<CollectionCard key={collection.id} collection={collection} />
))}
</div>
</div>
</div>
);
};
export default Collections;

24
components/Footer.tsx Normal file
View File

@@ -0,0 +1,24 @@
import React from 'react';
const Footer: React.FC = () => {
return (
<footer className="bg-gray-100 text-gray-800 py-12">
<div className="container mx-auto px-4 text-center">
<h3
className="text-2xl font-bold mb-4"
style={{fontFamily: 'Space Grotesk, sans-serif'}}
>
Store
</h3>
<p className="text-gray-500 mb-6">
Your premium shopping destination
</p>
<div className="mt-8 pt-8 text-gray-500">
<p>&copy; 2025 Store. All rights reserved.</p>
</div>
</div>
</footer>
);
};
export default Footer;

53
components/Header.tsx Normal file
View File

@@ -0,0 +1,53 @@
"use client";
import React from 'react';
import Link from 'next/link';
import { RiShoppingBagLine } from '@remixicon/react';
import { useShopifyCart } from '@/hooks/use-shopify-cart';
import config from '../lib/config.json';
const CartIcon: React.FC = () => {
const { itemCount, toggleCart } = useShopifyCart();
return (
<button
onClick={toggleCart}
className="relative p-2 text-black hover:text-gray-600 transition-colors"
>
<RiShoppingBagLine className="text-2xl" />
{itemCount > 0 && (
<span className="absolute -top-1 -right-1 bg-black text-white text-xs rounded-full w-6 h-6 flex items-center justify-center font-semibold">
{itemCount > 99 ? '99+' : itemCount}
</span>
)}
</button>
);
};
const Header: React.FC = () => {
return (
<nav className="bg-white shadow-sm sticky top-0 z-30 h-16">
<div className="container mx-auto px-4 h-full">
<div className="flex justify-between items-center h-full">
{/* Logo */}
<Link href="/" className="text-2xl font-bold text-black font-heading">
{config.brand.logo.url ? (
<img
src={config.brand.logo.url}
alt={config.brand.logo.alt || 'Store'}
className="h-8"
/>
) : (
'Store'
)}
</Link>
{/* Cart Icon */}
<CartIcon />
</div>
</div>
</nav>
);
};
export default Header;

21
components/Home.tsx Normal file
View File

@@ -0,0 +1,21 @@
import React from 'react';
import Header from './Header';
import Footer from './Footer';
import CollectionDetail from './CollectionDetail';
import config from '../lib/config.json';
const Home: React.FC = () => {
const collectionHandle = config.data.collection;
return (
<div className="flex flex-col min-h-screen">
<Header />
<main className="flex-1">
<CollectionDetail collectionHandle={collectionHandle} />
</main>
<Footer />
</div>
);
};
export default Home;

148
components/ProductCard.tsx Normal file
View File

@@ -0,0 +1,148 @@
"use client";
import React from 'react';
import { useShopifyCart } from '@/hooks/use-shopify-cart';
import { truncate } from '../lib/utils';
import { Card, CardContent } from './ui/card';
import { Button } from './ui/button';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductPrice {
amount: string;
currencyCode: string;
}
interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
}
interface Product {
id: string;
title: string;
description?: string;
handle: string;
images: {
edges: Array<{
node: ProductImage;
}>;
};
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
variants: {
edges: Array<{
node: ProductVariant;
}>;
};
}
interface ProductCardProps {
product: Product;
onAddToCart?: (product: Product) => void;
onClick?: (product: Product) => void;
}
const ProductCard: React.FC<ProductCardProps> = ({ product, onAddToCart, onClick }) => {
const { addItem, openCart } = useShopifyCart();
const firstImage = product.images.edges[0]?.node;
const price = product.priceRange.minVariantPrice;
const compareAtPrice = product.compareAtPriceRange?.minVariantPrice;
const hasDiscount = compareAtPrice && parseFloat(compareAtPrice.amount) > parseFloat(price.amount);
const firstVariant = product.variants.edges[0]?.node;
const isAvailable = firstVariant?.availableForSale || false;
const handleAddToCart = async (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (!firstVariant || !isAvailable) return;
try {
await addItem(firstVariant.id, 1);
openCart();
if (onAddToCart) {
onAddToCart(product);
}
} catch (error) {
console.error('Failed to add item to cart:', error);
}
};
return (
<Card className="!py-0 !gap-0 rounded-xs overflow-hidden hover:shadow-xl transition-shadow duration-300 group">
{/* Product Image */}
<div
className="aspect-square overflow-hidden bg-gray-100 relative cursor-pointer"
onClick={() => {
if (onClick) {
onClick(product);
}
}}
>
{firstImage ? (
<img
src={firstImage.url}
alt={firstImage.altText || product.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400">
<i className="ri-image-line text-6xl"></i>
</div>
)}
{/* Discount Badge */}
{hasDiscount && compareAtPrice && (
<div className="absolute top-3 left-3 bg-red-500 text-white text-xs font-semibold px-2 py-1 rounded">
{Math.round(((parseFloat(compareAtPrice.amount) - parseFloat(price.amount)) / parseFloat(compareAtPrice.amount)) * 100)}% OFF
</div>
)}
</div>
{/* Product Info */}
<CardContent className="p-6">
<h3 className="text-xl font-semibold text-gray-900 mb-2 font-heading">
{truncate(product.title, 60)}
</h3>
{/* Price Section */}
<div className="flex items-center justify-between mb-4">
<div>
<span className="text-sm font-bold text-muted-foreground">
${parseFloat(price.amount).toFixed(2)}
</span>
</div>
</div>
{/* View Details Button */}
<Button
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
if (onClick) {
onClick(product);
}
}}
className="w-full"
size="lg"
>
View Details
</Button>
</CardContent>
</Card>
);
};
export default ProductCard;

106
components/ProductModal.tsx Normal file
View File

@@ -0,0 +1,106 @@
"use client";
import React, { useEffect } from 'react';
import ProductDetail from './product-detail/ProductDetail';
import { Button } from './ui/button';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductPrice {
amount: string;
currencyCode: string;
}
interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
}
interface Product {
id: string;
title: string;
description?: string;
handle: string;
images: {
edges: Array<{
node: ProductImage;
}>;
};
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
variants: {
edges: Array<{
node: ProductVariant;
}>;
};
}
interface ProductModalProps {
product: Product;
isOpen: boolean;
onClose: () => void;
}
const ProductModal: React.FC<ProductModalProps> = ({ product, isOpen, onClose }) => {
// Close modal on ESC key press
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
onClose();
}
};
if (isOpen) {
document.addEventListener('keydown', handleEscape);
document.body.style.overflow = 'hidden';
}
return () => {
document.removeEventListener('keydown', handleEscape);
document.body.style.overflow = 'unset';
};
}, [isOpen, onClose]);
const handleBackdropClick = (e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onClose();
}
};
if (!isOpen) return null;
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4"
onClick={handleBackdropClick}
>
<div className="bg-white rounded-lg shadow-2xl max-w-7xl w-full max-h-[90vh] overflow-y-auto relative">
{/* Close Button */}
<Button
onClick={onClose}
variant="ghost"
size="icon"
className="absolute top-4 right-4 z-10 bg-white rounded-full hover:bg-gray-100"
aria-label="Close modal"
>
<i className="ri-close-line text-2xl text-gray-700"></i>
</Button>
{/* Product Detail Component */}
<ProductDetail handle={product.handle} onAddToCart={onClose} />
</div>
</div>
);
};
export default ProductModal;

248
components/Products.tsx Normal file
View File

@@ -0,0 +1,248 @@
"use client";
import React, { useState, useEffect } from 'react';
import ProductCard from './ProductCard';
import { getProducts } from '@/hooks/use-shopify-products';
import { Button } from './ui/button';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductPrice {
amount: string;
currencyCode: string;
}
interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
}
interface Product {
id: string;
title: string;
description?: string;
handle: string;
images: {
edges: Array<{
node: ProductImage;
}>;
};
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
variants: {
edges: Array<{
node: ProductVariant;
}>;
};
}
interface ProductsProps {
title?: string;
limit?: number;
showLoadMore?: boolean;
onViewDetails?: (product: Product) => void;
}
const Products: React.FC<ProductsProps> = ({
title = "Our Products",
limit = 12,
showLoadMore = true,
onViewDetails
}) => {
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [loadingMore, setLoadingMore] = useState(false);
const [hasMoreProducts, setHasMoreProducts] = useState(true);
const fetchProducts = async (currentProducts: Product[] = [], loadMore = false) => {
try {
if (loadMore) {
setLoadingMore(true);
} else {
setLoading(true);
setError(null);
}
const newProducts = await getProducts({
first: limit,
sortKey: 'CREATED_AT',
reverse: true
});
if (loadMore) {
// Filter out products that already exist
const existingIds = new Set(currentProducts.map(p => p.id));
const uniqueNewProducts = newProducts.filter(p => !existingIds.has(p.id));
if (uniqueNewProducts.length === 0) {
setHasMoreProducts(false);
} else {
setProducts(prev => [...prev, ...uniqueNewProducts]);
}
} else {
setProducts(newProducts);
setHasMoreProducts(newProducts.length === limit);
}
} catch (err) {
console.error('Error fetching products:', err);
setError(err instanceof Error ? err.message : 'Failed to load products');
} finally {
setLoading(false);
setLoadingMore(false);
}
};
useEffect(() => {
fetchProducts();
}, [limit]);
const handleAddToCart = async (product: Product) => {
// Here you would typically integrate with cart functionality
console.log('Adding to cart:', product);
};
const handleLoadMore = () => {
if (!loadingMore && hasMoreProducts) {
fetchProducts(products, true);
}
};
if (loading) {
return (
<div className="py-16">
<div className="max-w-7xl mx-auto px-4">
<h2
className="text-4xl font-bold text-center mb-12 font-heading"
>
{title}
</h2>
{/* Loading Skeleton */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{Array.from({ length: 8 }).map((_, index) => (
<div key={index} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
<div className="aspect-square bg-gray-200"></div>
<div className="p-6">
<div className="h-6 bg-gray-200 rounded mb-2"></div>
<div className="h-4 bg-gray-200 rounded mb-4"></div>
<div className="h-8 bg-gray-200 rounded mb-4"></div>
<div className="h-12 bg-gray-200 rounded"></div>
</div>
</div>
))}
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="py-16">
<div className="max-w-7xl mx-auto px-4 text-center">
<h2
className="text-4xl font-bold mb-8 font-heading"
>
{title}
</h2>
<div className="bg-red-50 border border-red-200 rounded-lg p-8 max-w-md mx-auto">
<i className="ri-error-warning-line text-4xl text-red-500 mb-4"></i>
<h3 className="text-lg font-semibold text-red-800 mb-2">
Failed to Load Products
</h3>
<p className="text-red-600 mb-4">
{error}
</p>
<Button
onClick={() => fetchProducts()}
variant="destructive"
>
Try Again
</Button>
</div>
</div>
</div>
);
}
if (products.length === 0) {
return (
<div className="py-16">
<div className="max-w-7xl mx-auto px-4 text-center">
<h2
className="text-4xl font-bold mb-8 font-heading"
>
{title}
</h2>
<div className="bg-gray-50 border border-gray-200 rounded-lg p-8 max-w-md mx-auto">
<i className="ri-shopping-bag-line text-4xl text-gray-400 mb-4"></i>
<h3 className="text-lg font-semibold text-gray-600 mb-2">
No Products Found
</h3>
<p className="text-gray-500">
Check back later or configure your Shopify store connection.
</p>
</div>
</div>
</div>
);
}
return (
<div className="py-16 bg-gray-50">
<div className="max-w-7xl mx-auto px-4">
<h2
className="text-5xl font-bold text-center mb-16 text-gray-900 font-heading"
>
{title}
</h2>
{/* Products Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8 mb-12">
{products.map((product) => (
<ProductCard
key={product.id}
product={product}
onAddToCart={handleAddToCart}
onClick={onViewDetails}
/>
))}
</div>
{/* Load More Button */}
{showLoadMore && hasMoreProducts && (
<div className="text-center">
<Button
onClick={handleLoadMore}
disabled={loadingMore}
size="lg"
>
{loadingMore ? (
<span className="flex items-center space-x-2">
<i className="ri-loader-4-line animate-spin"></i>
<span>Loading...</span>
</span>
) : (
'Load More Products'
)}
</Button>
</div>
)}
</div>
</div>
);
};
export default Products;

123
components/Theme.tsx Normal file
View File

@@ -0,0 +1,123 @@
import React from 'react';
import config from '../lib/config.json';
const Theme: React.FC = () => {
const headerFont = config.brand.fonts.header;
const bodyFont = config.brand.fonts.body;
const primaryColor = config.brand.colors.primary;
const secondaryColor = config.brand.colors.secondary;
return (
<>
{/* Font Imports */}
<link
href={`https://fonts.googleapis.com/css2?family=${headerFont}:wght@400;500;600;700;800&display=swap`}
rel="stylesheet"
/>
<link
href={`https://fonts.googleapis.com/css2?family=${bodyFont}:wght@300;400;500;600;700&display=swap`}
rel="stylesheet"
/>
{/* Tailwind Browser Script */}
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4?plugins=typography,forms"></script>
{/* Theme Styles */}
<style type="text/tailwindcss">
{`
@theme {
/* Background and foreground */
--color-background: hsl(0 0% 100%);
--color-foreground: hsl(222.2 84% 4.9%);
/* Card */
--color-card: hsl(0 0% 100%);
--color-card-foreground: hsl(222.2 84% 4.9%);
/* Popover */
--color-popover: hsl(0 0% 100%);
--color-popover-foreground: hsl(222.2 84% 4.9%);
/* Primary */
--color-primary: ${primaryColor};
--color-primary-foreground: hsl(210 40% 98%);
/* Secondary */
--color-secondary: ${secondaryColor};
--color-secondary-foreground: hsl(222.2 47.4% 11.2%);
/* Muted */
--color-muted: hsl(210 40% 96.1%);
--color-muted-foreground: hsl(215.4 16.3% 46.9%);
/* Accent */
--color-accent: hsl(210 40% 96.1%);
--color-accent-foreground: hsl(222.2 47.4% 11.2%);
/* Destructive */
--color-destructive: hsl(0 84.2% 60.2%);
--color-destructive-foreground: hsl(210 40% 98%);
/* Border, input, ring */
--color-border: hsl(214.3 31.8% 91.4%);
--color-input: hsl(214.3 31.8% 91.4%);
--color-ring: hsl(222.2 84% 4.9%);
/* Sidebar */
--color-sidebar: hsl(0 0% 98%);
--color-sidebar-foreground: hsl(240 5.3% 26.1%);
--color-sidebar-primary: hsl(240 5.9% 10%);
--color-sidebar-primary-foreground: hsl(0 0% 98%);
--color-sidebar-accent: hsl(240 4.8% 95.9%);
--color-sidebar-accent-foreground: hsl(240 5.9% 10%);
--color-sidebar-border: hsl(220 13% 91%);
--color-sidebar-ring: hsl(217.2 91.2% 59.8%);
/* Border radius */
--radius-sm: 0.25rem;
--radius-md: 0.375rem;
--radius-lg: 0.5rem;
--radius-xl: 0.75rem;
/* Fonts from config */
--font-heading: "${headerFont.replace(/\+/g, ' ')}", sans-serif;
--font-body: "${bodyFont.replace(/\+/g, ' ')}", sans-serif;
}
/* Dark mode */
.dark {
--color-background: hsl(222.2 84% 4.9%);
--color-foreground: hsl(210 40% 98%);
--color-card: hsl(222.2 84% 4.9%);
--color-card-foreground: hsl(210 40% 98%);
--color-popover: hsl(222.2 84% 4.9%);
--color-popover-foreground: hsl(210 40% 98%);
--color-primary: hsl(210 40% 98%);
--color-primary-foreground: hsl(222.2 47.4% 11.2%);
--color-secondary: hsl(217.2 32.6% 17.5%);
--color-secondary-foreground: hsl(210 40% 98%);
--color-muted: hsl(217.2 32.6% 17.5%);
--color-muted-foreground: hsl(215 20.2% 65.1%);
--color-accent: hsl(217.2 32.6% 17.5%);
--color-accent-foreground: hsl(210 40% 98%);
--color-destructive: hsl(0 62.8% 30.6%);
--color-destructive-foreground: hsl(210 40% 98%);
--color-border: hsl(217.2 32.6% 17.5%);
--color-input: hsl(217.2 32.6% 17.5%);
--color-ring: hsl(212.7 26.8% 83.9%);
--color-sidebar: hsl(240 5.9% 10%);
--color-sidebar-foreground: hsl(240 4.8% 95.9%);
--color-sidebar-primary: hsl(224.3 76.3% 48%);
--color-sidebar-primary-foreground: hsl(0 0% 100%);
--color-sidebar-accent: hsl(240 3.7% 15.9%);
--color-sidebar-accent-foreground: hsl(240 4.8% 95.9%);
--color-sidebar-border: hsl(240 3.7% 15.9%);
--color-sidebar-ring: hsl(217.2 91.2% 59.8%);
}
`}
</style>
</>
);
};
export default Theme;

View File

@@ -0,0 +1,40 @@
import React, { memo } from 'react';
import { cn } from '@/lib/utils';
interface AuroraTextProps {
children: React.ReactNode;
className?: string;
colors?: string[];
speed?: number;
}
export const AuroraText = memo(
({
children,
className,
colors = ['#FF0080', '#7928CA', '#0070F3', '#38bdf8'],
speed = 1,
}: AuroraTextProps) => {
const animationDuration = `${10 / speed}s`;
const gradientStyle = {
backgroundImage: `linear-gradient(90deg, ${colors.join(', ')}, ${colors[0]})`,
backgroundSize: '200% 100%',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
backgroundClip: 'text',
animation: `aurora-flow ${animationDuration} ease-in-out infinite`,
} as React.CSSProperties;
return (
<span className={cn('relative inline-block', className)}>
<span className="sr-only">{children}</span>
<span className="relative" style={gradientStyle} aria-hidden="true">
{children}
</span>
</span>
);
}
);
AuroraText.displayName = 'AuroraText';

View File

@@ -0,0 +1,63 @@
import React from 'react';
import { useRef, useEffect, useState } from 'react';
import { cn } from '@/lib/utils';
interface BlurFadeProps {
children: React.ReactNode;
className?: string;
duration?: number;
delay?: number;
inView?: boolean;
}
export function BlurFade({
children,
className,
duration = 0.4,
delay = 0,
inView = false,
}: BlurFadeProps) {
const ref = useRef<HTMLDivElement>(null);
const [isVisible, setIsVisible] = useState(!inView);
useEffect(() => {
if (!inView) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.unobserve(entry.target);
}
},
{ threshold: 0.1, rootMargin: '-50px' }
);
if (ref.current) {
observer.observe(ref.current);
}
return () => {
if (ref.current) {
observer.unobserve(ref.current);
}
};
}, [inView]);
return (
<div
ref={ref}
className={cn(
isVisible ? 'opacity-100 blur-none' : 'opacity-0 blur-sm',
className
)}
style={{
animation: isVisible
? `blur-fade ${duration}s ease-out ${delay}s forwards`
: 'none',
}}
>
{children}
</div>
);
}

View File

@@ -0,0 +1,240 @@
"use client";
import React, { useState, useEffect } from 'react';
import { getProduct } from '@/hooks/use-shopify-products';
import { useShopifyCart } from '@/hooks/use-shopify-cart';
import ProductDetailGallery from './ProductDetailGallery';
import ProductDetailInfo from './ProductDetailInfo';
import { Button } from '../ui/button';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductPrice {
amount: string;
currencyCode: string;
}
export interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
selectedOptions: Array<{
name: string;
value: string;
}>;
image?: {
url: string;
altText?: string;
};
}
interface ProductOption {
id: string;
name: string;
values: string[];
}
export interface Product {
id: string;
title: string;
description?: string;
descriptionHtml?: string;
handle: string;
images: {
edges: Array<{
node: ProductImage;
}>;
};
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
variants: {
edges: Array<{
node: ProductVariant;
}>;
};
options: ProductOption[];
}
type ProductDetailProps = {
handle: string;
onAddToCart?: () => void;
}
const ProductDetail: React.FC<ProductDetailProps> = ({ handle, onAddToCart: onAddToCartCallback }) => {
const { addItem, openCart } = useShopifyCart();
const [product, setProduct] = useState<Product | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedVariant, setSelectedVariant] = useState<ProductVariant | null>(null);
const [selectedOptions, setSelectedOptions] = useState<Record<string, string>>({});
const [quantity, setQuantity] = useState(1);
const [selectedImageIndex, setSelectedImageIndex] = useState(0);
const [isAddingToCart, setIsAddingToCart] = useState(false);
useEffect(() => {
if (!handle) return;
const fetchProduct = async () => {
try {
setLoading(true);
setError(null);
const productData = await getProduct(handle);
if (!productData) {
setError('Product not found');
return;
}
setProduct(productData);
// Set default variant
const firstVariant = productData.variants.edges[0]?.node;
if (firstVariant) {
setSelectedVariant(firstVariant);
// Initialize selected options
const initialOptions: Record<string, string> = {};
firstVariant.selectedOptions.forEach(option => {
initialOptions[option.name] = option.value;
});
setSelectedOptions(initialOptions);
}
} catch (err) {
console.error('Error fetching product:', err);
setError(err instanceof Error ? err.message : 'Failed to load product');
} finally {
setLoading(false);
}
};
fetchProduct();
}, [handle]);
const handleOptionChange = (optionName: string, value: string) => {
const newOptions = { ...selectedOptions, [optionName]: value };
setSelectedOptions(newOptions);
// Find matching variant
const matchingVariant = product?.variants.edges.find(({ node }) => {
return node.selectedOptions.every(option =>
newOptions[option.name] === option.value
);
});
if (matchingVariant) {
setSelectedVariant(matchingVariant.node);
// Update image if variant has an associated image
if (matchingVariant.node.image && product) {
const imageIndex = product.images.edges.findIndex(
({ node }) => node.url === matchingVariant.node.image?.url
);
if (imageIndex !== -1) {
setSelectedImageIndex(imageIndex);
}
}
}
};
const handleAddToCart = async () => {
if (!selectedVariant || !product) return;
setIsAddingToCart(true);
try {
await addItem(selectedVariant.id, quantity);
openCart();
if (onAddToCartCallback) {
onAddToCartCallback();
}
} catch (error) {
console.error('Failed to add item to cart:', error);
} finally {
setIsAddingToCart(false);
}
};
if (loading) {
return (
<div className="container mx-auto px-4 py-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
{/* Image Gallery Skeleton */}
<div>
<div className="aspect-square bg-gray-200 rounded-lg animate-pulse mb-4"></div>
<div className="grid grid-cols-4 gap-2">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="aspect-square bg-gray-200 rounded animate-pulse"></div>
))}
</div>
</div>
{/* Product Info Skeleton */}
<div>
<div className="h-8 bg-gray-200 rounded mb-4 animate-pulse"></div>
<div className="h-6 bg-gray-200 rounded mb-6 w-1/3 animate-pulse"></div>
<div className="h-24 bg-gray-200 rounded mb-6 animate-pulse"></div>
<div className="h-12 bg-gray-200 rounded mb-4 animate-pulse"></div>
<div className="h-12 bg-gray-200 rounded animate-pulse"></div>
</div>
</div>
</div>
);
}
if (error || !product) {
return (
<div className="container mx-auto px-4 py-8 text-center">
<div className="bg-red-50 border border-red-200 rounded-lg p-8 max-w-md mx-auto">
<i className="ri-error-warning-line text-4xl text-red-500 mb-4"></i>
<h3 className="text-lg font-semibold text-red-800 mb-2">
Product Not Found
</h3>
<p className="text-red-600 mb-4">
{error || 'The requested product could not be found.'}
</p>
<Button
onClick={() => window.history.back()}
variant="destructive"
>
Go Back
</Button>
</div>
</div>
);
}
return (
<div className="bg-white">
<div className="container mx-auto px-4 py-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
<ProductDetailGallery
images={product.images.edges.map(edge => edge.node)}
selectedImageIndex={selectedImageIndex}
onImageChange={setSelectedImageIndex}
/>
<ProductDetailInfo
product={product}
selectedVariant={selectedVariant}
selectedOptions={selectedOptions}
quantity={quantity}
setQuantity={setQuantity}
handleAddToCart={handleAddToCart}
onOptionChange={handleOptionChange}
isAddingToCart={isAddingToCart}
/>
</div>
</div>
</div>
);
};
export default ProductDetail;

View File

@@ -0,0 +1,59 @@
import React from 'react';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductDetailGalleryProps {
images: ProductImage[];
selectedImageIndex: number;
onImageChange: (index: number) => void;
}
const ProductDetailGallery: React.FC<ProductDetailGalleryProps> = ({ images, selectedImageIndex, onImageChange }) => {
return (
<div>
{/* Main Image */}
<div className="aspect-square bg-gray-100 rounded-lg overflow-hidden mb-4">
{images.length > 0 ? (
<img
src={images[selectedImageIndex].url}
alt={images[selectedImageIndex].altText || 'Product image'}
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400">
<i className="ri-image-line text-6xl"></i>
</div>
)}
</div>
{/* Image Thumbnails */}
{images.length > 1 && (
<div className="grid grid-cols-4 gap-2">
{images.map((image, index) => (
<button
key={index}
onClick={() => onImageChange(index)}
className={`aspect-square rounded-lg overflow-hidden border-2 transition-colors ${
selectedImageIndex === index
? 'border-black'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<img
src={image.url}
alt={image.altText || 'Product thumbnail'}
className="w-full h-full object-cover"
/>
</button>
))}
</div>
)}
</div>
);
};
export default ProductDetailGallery;

View File

@@ -0,0 +1,159 @@
import React from 'react';
import { RiSubtractLine, RiAddLine, RiTruckLine, RiArrowGoBackLine, RiSecurePaymentLine, RiLoader4Line } from '@remixicon/react';
import { Product, ProductVariant } from './ProductDetail.tsx';
import { Button } from '../ui/button';
interface ProductDetailInfoProps {
product: Product;
selectedVariant: ProductVariant | null;
selectedOptions: Record<string, string>;
quantity: number;
setQuantity: (quantity: number) => void;
handleAddToCart: () => void;
onOptionChange: (optionName: string, value: string) => void;
isAddingToCart?: boolean;
}
const ProductDetailInfo: React.FC<ProductDetailInfoProps> = ({
product,
selectedVariant,
selectedOptions,
quantity,
setQuantity,
handleAddToCart,
onOptionChange,
isAddingToCart = false
}) => {
const formatPrice = (price: { amount: string; currencyCode: string }) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(parseFloat(price.amount));
};
const price = selectedVariant?.price || product.priceRange.minVariantPrice;
const compareAtPrice = product.compareAtPriceRange?.minVariantPrice;
const hasDiscount = compareAtPrice && parseFloat(compareAtPrice.amount) > parseFloat(price.amount);
return (
<div>
<h1 className="text-4xl font-bold text-gray-900 mb-4 font-heading">
{product.title}
</h1>
{/* Price */}
<div className="flex items-center space-x-4 mb-6">
<span className="text-2xl font-bold text-gray-900">
{formatPrice(price)}
</span>
{hasDiscount && compareAtPrice && (
<>
<span className="text-xl text-gray-500 line-through">
{formatPrice(compareAtPrice)}
</span>
<div className="bg-red-100 text-red-800 text-sm font-semibold px-3 py-1 rounded">
{Math.round(((parseFloat(compareAtPrice.amount) - parseFloat(price.amount)) / parseFloat(compareAtPrice.amount)) * 100)}% OFF
</div>
</>
)}
</div>
{/* Description */}
{product.description && (
<div className="text-gray-600 mb-8 text-lg leading-relaxed">
{product.descriptionHtml ? (
<div dangerouslySetInnerHTML={{ __html: product.descriptionHtml }} />
) : (
<p>{product.description}</p>
)}
</div>
)}
{/* Product Options */}
{product.options
.filter(option => option.name !== 'Title')
.map(option => (
<div key={option.id} className="mb-6">
<label className="block text-sm font-semibold text-gray-700 mb-2">
{option.name}
</label>
<div className="flex flex-wrap gap-2">
{option.values.map(value => (
<Button
key={value}
onClick={() => onOptionChange(option.name, value)}
variant={selectedOptions[option.name] === value ? 'default' : 'outline'}
>
{value}
</Button>
))}
</div>
</div>
))}
{/* Quantity Selector */}
<div className="mb-8">
<label className="block text-sm font-semibold text-gray-700 mb-2">
Quantity
</label>
<div className="flex items-center border border-gray-300 rounded-lg w-32">
<Button
onClick={() => setQuantity(Math.max(1, quantity - 1))}
variant="ghost"
size="icon-sm"
disabled={quantity <= 1}
>
<RiSubtractLine />
</Button>
<span className="flex-1 text-center font-semibold text-sm">{quantity}</span>
<Button
onClick={() => setQuantity(quantity + 1)}
variant="ghost"
size="icon-sm"
>
<RiAddLine />
</Button>
</div>
</div>
{/* Add to Cart Button */}
<Button
onClick={handleAddToCart}
disabled={!selectedVariant?.availableForSale || isAddingToCart}
size="lg"
className="w-full py-4 text-lg"
>
{isAddingToCart ? (
<span className="flex items-center justify-center gap-2">
<RiLoader4Line className="animate-spin" />
Adding...
</span>
) : selectedVariant?.availableForSale ? (
'Add to Cart'
) : (
'Out of Stock'
)}
</Button>
{/* Additional Info */}
<div className="mt-8 pt-8 border-t border-gray-200">
<div className="space-y-3 text-sm text-gray-600">
<div className="flex items-center space-x-2">
<RiTruckLine />
<span>Free shipping on orders over $100</span>
</div>
<div className="flex items-center space-x-2">
<RiArrowGoBackLine />
<span>30-day return policy</span>
</div>
<div className="flex items-center space-x-2">
<RiSecurePaymentLine />
<span>Secure payment</span>
</div>
</div>
</div>
</div>
);
};
export default ProductDetailInfo;

View File

@@ -0,0 +1,85 @@
"use client";
import React, { useState, useEffect } from 'react';
import { getProductRecommendations } from '@/hooks/use-shopify-products';
import ProductCard from '../ProductCard';
interface ProductRecommendationsProps {
productId: string;
}
const ProductRecommendations: React.FC<ProductRecommendationsProps> = ({ productId }) => {
const [recommendedProducts, setRecommendedProducts] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchRecommendations = async () => {
if (!productId) return;
try {
setLoading(true);
setError(null);
const recommendations = await getProductRecommendations(productId);
setRecommendedProducts(recommendations);
} catch (err) {
console.error('Error fetching product recommendations:', err);
setError(err instanceof Error ? err.message : 'Failed to load recommendations');
} finally {
setLoading(false);
}
};
fetchRecommendations();
}, [productId]);
// Don't show section if we're not loading and have no recommendations
if (!loading && (!recommendedProducts || recommendedProducts.length === 0)) {
return null;
}
return (
<div className="bg-gray-50 py-16">
<div className="container mx-auto px-4">
<h2
className="text-4xl font-bold text-center mb-12 text-gray-900"
style={{ fontFamily: 'Space Grotesk, sans-serif' }}
>
You Might Also Like
</h2>
{loading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{Array.from({ length: 4 }).map((_, index) => (
<div key={index} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
<div className="aspect-square bg-gray-200"></div>
<div className="p-6">
<div className="h-6 bg-gray-200 rounded mb-2"></div>
<div className="h-4 bg-gray-200 rounded mb-4"></div>
<div className="h-8 bg-gray-200 rounded mb-4"></div>
<div className="h-12 bg-gray-200 rounded"></div>
</div>
</div>
))}
</div>
) : error ? (
<div className="text-center py-8">
<p className="text-gray-500">Recommendations could not be loaded</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{recommendedProducts.slice(0, 4).map((recommendedProduct) => (
<ProductCard
key={recommendedProduct.id}
product={recommendedProduct}
/>
))}
</div>
)}
</div>
</div>
);
};
export default ProductRecommendations;

197
components/ui/accordion.tsx Normal file
View File

@@ -0,0 +1,197 @@
import React, { createContext, useContext, useState, useCallback } from 'react';
import { cn } from '@/lib/utils';
interface AccordionContextType {
value: string | string[];
onValueChange: (value: string) => void;
type: 'single' | 'multiple';
}
const AccordionContext = createContext<AccordionContextType | undefined>(
undefined
);
interface AccordionItemContextType {
value: string;
}
const AccordionItemContext = createContext<
AccordionItemContextType | undefined
>(undefined);
function useAccordion() {
const context = useContext(AccordionContext);
if (!context) {
throw new Error('Accordion components must be used within an Accordion');
}
return context;
}
function useAccordionItem() {
const context = useContext(AccordionItemContext);
if (!context) {
throw new Error(
'AccordionTrigger and AccordionContent must be used within an AccordionItem'
);
}
return context;
}
interface AccordionProps {
type?: 'single' | 'multiple';
value?: string | string[];
onValueChange?: (value: string | string[]) => void;
children: React.ReactNode;
}
function Accordion({
type = 'single',
value: controlledValue,
onValueChange,
children,
}: AccordionProps) {
const [internalValue, setInternalValue] = useState<string | string[]>(
type === 'single' ? '' : []
);
const isControlled = controlledValue !== undefined;
const value = isControlled ? controlledValue : internalValue;
const handleValueChange = useCallback(
(itemValue: string) => {
if (type === 'single') {
const newValue = value === itemValue ? '' : itemValue;
if (!isControlled) {
setInternalValue(newValue);
}
onValueChange?.(newValue);
} else {
const valueArray = Array.isArray(value) ? value : [];
const newValue = valueArray.includes(itemValue)
? valueArray.filter((v) => v !== itemValue)
: [...valueArray, itemValue];
if (!isControlled) {
setInternalValue(newValue);
}
onValueChange?.(newValue);
}
},
[value, type, isControlled, onValueChange]
);
return (
<AccordionContext.Provider
value={{ value, onValueChange: handleValueChange, type }}
>
<div data-slot="accordion">{children}</div>
</AccordionContext.Provider>
);
}
interface AccordionItemProps {
value: string;
children: React.ReactNode;
className?: string;
}
function AccordionItem({ value, children, className }: AccordionItemProps) {
return (
<AccordionItemContext.Provider value={{ value }}>
<div
data-slot="accordion-item"
className={cn('border-b border-border last:border-b-0', className)}
data-value={value}
>
{children}
</div>
</AccordionItemContext.Provider>
);
}
interface AccordionTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
children: React.ReactNode;
}
function AccordionTrigger({
className,
children,
...props
}: AccordionTriggerProps) {
const accordion = useAccordion();
const item = useAccordionItem();
const handleClick = () => {
accordion.onValueChange(item.value);
};
const isOpen =
accordion.type === 'single'
? accordion.value === item.value
: Array.isArray(accordion.value) && accordion.value.includes(item.value);
return (
<div className="flex">
<button
data-slot="accordion-trigger"
className={cn(
'flex flex-1 items-start justify-between gap-4 rounded-md py-4 px-0 text-left text-sm font-medium transition-all outline-none hover:cursor-pointer focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:rounded-md disabled:pointer-events-none disabled:opacity-50',
isOpen && '[&>svg]:rotate-180',
className
)}
onClick={handleClick}
data-state={isOpen ? 'open' : 'closed'}
{...props}
>
{children}
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200"
>
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
</div>
);
}
interface AccordionContentProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
function AccordionContent({
className,
children,
...props
}: AccordionContentProps) {
const accordion = useAccordion();
const item = useAccordionItem();
const isOpen =
accordion.type === 'single'
? accordion.value === item.value
: Array.isArray(accordion.value) && accordion.value.includes(item.value);
return (
<div
data-slot="accordion-content"
data-state={isOpen ? 'open' : 'closed'}
className={cn(
'overflow-hidden text-sm transition-all duration-200',
isOpen ? 'max-h-96' : 'max-h-0'
)}
{...props}
>
<div className={cn('pt-0 pb-4', className)}>{children}</div>
</div>
);
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };

60
components/ui/alert.tsx Normal file
View File

@@ -0,0 +1,60 @@
import * as React from "react"
import { cn } from "@/lib/utils"
type AlertVariant = "default" | "destructive"
const baseClasses =
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current"
const variantClasses: Record<AlertVariant, string> = {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
}
function Alert({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & { variant?: AlertVariant }) {
return (
<div
data-slot="alert"
role="alert"
className={cn(baseClasses, variantClasses[variant], className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

81
components/ui/avatar.tsx Normal file
View File

@@ -0,0 +1,81 @@
import React from 'react';
import { cn } from '@/lib/utils';
interface AvatarProps extends React.ComponentProps<'div'> {
size?: 'sm' | 'md' | 'lg' | 'xl';
}
const sizeClasses = {
sm: 'size-6',
md: 'size-8',
lg: 'size-10',
xl: 'size-12',
};
function Avatar({ className, size = 'md', ...props }: AvatarProps) {
const [imageError, setImageError] = React.useState(false);
return (
<div
data-slot="avatar"
className={cn(
'relative flex shrink-0 overflow-hidden rounded-full',
sizeClasses[size],
className
)}
{...props}
/>
);
}
function AvatarImage({
className,
onError,
...props
}: React.ComponentProps<'img'>) {
const [hasError, setHasError] = React.useState(false);
const handleError = (e: React.SyntheticEvent<HTMLImageElement>) => {
setHasError(true);
onError?.(e as any);
};
if (hasError) {
return null;
}
return (
<img
data-slot="avatar-image"
className={cn('aspect-square h-full w-full object-cover', className)}
onError={handleError}
{...props}
/>
);
}
interface AvatarFallbackProps extends React.ComponentProps<'div'> {
children: React.ReactNode;
}
function AvatarFallback({
className,
children,
...props
}: AvatarFallbackProps) {
return (
<div
data-slot="avatar-fallback"
className={cn(
'bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full font-medium text-sm',
className
)}
{...props}
>
{children}
</div>
);
}
export { Avatar, AvatarImage, AvatarFallback };
export type { AvatarProps };

53
components/ui/badge.tsx Normal file
View File

@@ -0,0 +1,53 @@
import React from 'react';
import { cn } from '@/lib/utils';
type BadgeVariant = 'default' | 'secondary' | 'destructive' | 'outline';
interface BadgeProps extends React.ComponentProps<'span'> {
variant?: BadgeVariant;
asChild?: boolean;
}
const badgeVariants: Record<BadgeVariant, string> = {
default:
'border-transparent bg-primary text-primary-foreground hover:bg-primary/90',
secondary:
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/90',
destructive:
'border-transparent bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
outline:
'text-foreground border-border hover:bg-accent hover:text-accent-foreground',
};
function Badge({
className,
variant = 'default',
asChild = false,
children,
...props
}: BadgeProps) {
const baseClasses = cn(
'inline-flex items-center justify-center rounded-full border px-2.5 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 gap-1 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-colors overflow-hidden',
'[&>svg]:size-3 [&>svg]:pointer-events-none [&>svg]:shrink-0'
);
const variantClasses = badgeVariants[variant];
const finalClassName = cn(baseClasses, variantClasses, className);
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement, {
className: cn(children.props.className, finalClassName),
...props,
});
}
return (
<span data-slot="badge" className={finalClassName} {...props}>
{children}
</span>
);
}
export { Badge, badgeVariants };
export type { BadgeProps };

View File

@@ -0,0 +1,148 @@
import React from 'react';
import { cn } from '@/lib/utils';
function Breadcrumb({ ...props }: React.ComponentProps<'nav'>) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />;
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<'ol'>) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
'text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5',
className
)}
{...props}
/>
);
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="breadcrumb-item"
className={cn('inline-flex items-center gap-1.5', className)}
{...props}
/>
);
}
function BreadcrumbLink({
asChild,
className,
children,
...props
}: React.ComponentProps<'a'> & {
asChild?: boolean;
}) {
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement, {
className: cn(
'hover:text-foreground transition-colors',
children.props.className,
className
),
...props,
});
}
return (
<a
data-slot="breadcrumb-link"
className={cn('hover:text-foreground transition-colors', className)}
{...props}
>
{children}
</a>
);
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
className={cn('text-foreground font-normal', className)}
{...props}
/>
);
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<'li'>) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn('[&>svg]:size-3.5', className)}
{...props}
>
{children ?? (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-3.5"
>
<polyline points="9 18 15 12 9 6"></polyline>
</svg>
)}
</li>
);
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<'span'>) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn('flex size-9 items-center justify-center', className)}
{...props}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
>
<circle cx="12" cy="12" r="1"></circle>
<circle cx="19" cy="12" r="1"></circle>
<circle cx="5" cy="12" r="1"></circle>
</svg>
<span className="sr-only">More</span>
</span>
);
}
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};

View File

@@ -0,0 +1,97 @@
import React from 'react';
// Utility function to combine classNames
function cn(...classes: (string | undefined | null | false)[]): string {
return classes.filter(Boolean).join(' ');
}
// Button group variants helper
function getButtonGroupVariants(
orientation: 'horizontal' | 'vertical'
): string {
const baseStyles =
'flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*="w-"])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2';
const orientationStyles = {
horizontal:
'[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none',
vertical:
'flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none',
};
return cn(baseStyles, orientationStyles[orientation]);
}
interface ButtonGroupProps extends React.ComponentProps<'div'> {
orientation?: 'horizontal' | 'vertical';
}
function ButtonGroup({
className,
orientation = 'horizontal',
...props
}: ButtonGroupProps) {
return (
<div
role="group"
data-slot="button-group"
data-orientation={orientation}
className={cn(getButtonGroupVariants(orientation), className)}
{...props}
/>
);
}
interface ButtonGroupTextProps extends React.ComponentProps<'div'> {
asChild?: boolean;
}
function ButtonGroupText({
className,
asChild = false,
...props
}: ButtonGroupTextProps) {
const Comp = asChild ? 'div' : 'div';
return (
<Comp
data-slot="button-group-text"
className={cn(
'bg-muted flex items-center gap-2 rounded-md border border-border px-4 py-2 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*="size-"])]:size-4',
className
)}
{...props}
/>
);
}
interface ButtonGroupSeparatorProps extends React.ComponentProps<'div'> {
orientation?: 'horizontal' | 'vertical';
}
function ButtonGroupSeparator({
className,
orientation = 'vertical',
...props
}: ButtonGroupSeparatorProps) {
const separatorClasses =
orientation === 'vertical' ? 'w-px h-auto' : 'h-px w-auto';
return (
<div
data-slot="button-group-separator"
className={cn(
'bg-border relative !m-0 self-stretch',
separatorClasses,
className
)}
{...props}
/>
);
}
export { ButtonGroup, ButtonGroupSeparator, ButtonGroupText };
export type {
ButtonGroupProps,
ButtonGroupTextProps,
ButtonGroupSeparatorProps,
};

70
components/ui/button.tsx Normal file
View File

@@ -0,0 +1,70 @@
import React from 'react';
import { cn } from '@/lib/utils';
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?:
| 'default'
| 'destructive'
| 'outline'
| 'secondary'
| 'ghost'
| 'link';
size?: 'default' | 'sm' | 'lg' | 'icon' | 'icon-sm' | 'icon-lg';
children?: React.ReactNode;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant = 'default', size = 'default', ...props }, ref) => {
const baseClasses = cn(
// Base styles
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all',
'disabled:pointer-events-none disabled:opacity-50',
'[&_svg]:pointer-events-none [&_svg:not([class*="size-"])]:size-4',
'shrink-0 [&_svg]:shrink-0',
'outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive'
);
const variantClasses = {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive:
'bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
outline:
'border border-border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost:
'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
link: 'text-primary underline-offset-4 hover:underline',
};
const sizeClasses = {
default: 'h-9 px-4 py-2 has-[>svg]:px-3',
sm: 'h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5',
lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
icon: 'size-9',
'icon-sm': 'size-8',
'icon-lg': 'size-10',
};
return (
<button
ref={ref}
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(
baseClasses,
variantClasses[variant],
sizeClasses[size],
className
)}
{...props}
/>
);
}
);
Button.displayName = 'Button';
export { Button };
export default Button;

92
components/ui/card.tsx Normal file
View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border border-border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

245
components/ui/carousel.tsx Normal file
View File

@@ -0,0 +1,245 @@
import React, {
createContext,
useContext,
useState,
useCallback,
useRef,
useEffect,
} from 'react';
import { cn } from '@/lib/utils';
import { Button } from './button';
interface CarouselContextType {
currentIndex: number;
totalItems: number;
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
orientation: 'horizontal' | 'vertical';
}
const CarouselContext = createContext<CarouselContextType | undefined>(
undefined
);
function useCarousel() {
const context = useContext(CarouselContext);
if (!context) {
throw new Error('Carousel components must be used within a Carousel');
}
return context;
}
interface CarouselProps {
children: React.ReactNode;
orientation?: 'horizontal' | 'vertical';
className?: string;
autoPlay?: boolean;
autoPlayInterval?: number;
}
function Carousel({
children,
orientation = 'horizontal',
className,
autoPlay = false,
autoPlayInterval = 3000,
}: CarouselProps) {
const [currentIndex, setCurrentIndex] = useState(0);
const itemCount = React.Children.count(children);
const autoPlayTimerRef = useRef<NodeJS.Timeout | null>(null);
const canScrollPrev = currentIndex > 0;
const canScrollNext = currentIndex < itemCount - 1;
const scrollPrev = useCallback(() => {
setCurrentIndex((prev) => Math.max(0, prev - 1));
}, []);
const scrollNext = useCallback(() => {
setCurrentIndex((prev) => Math.min(itemCount - 1, prev + 1));
}, [itemCount]);
useEffect(() => {
if (!autoPlay) return;
autoPlayTimerRef.current = setInterval(() => {
setCurrentIndex((prev) => {
if (prev >= itemCount - 1) {
return 0;
}
return prev + 1;
});
}, autoPlayInterval);
return () => {
if (autoPlayTimerRef.current) {
clearInterval(autoPlayTimerRef.current);
}
};
}, [autoPlay, autoPlayInterval, itemCount]);
return (
<CarouselContext.Provider
value={{
currentIndex,
totalItems: itemCount,
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
orientation,
}}
>
<div
className={cn('relative', className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
>
{children}
</div>
</CarouselContext.Provider>
);
}
interface CarouselContentProps {
className?: string;
children: React.ReactNode;
}
function CarouselContent({ className, children }: CarouselContentProps) {
const { currentIndex, orientation } = useCarousel();
return (
<div
className={cn('overflow-hidden', className)}
data-slot="carousel-content"
>
<div
className={cn(
'flex transition-transform duration-300 ease-out',
orientation === 'horizontal' ? 'flex-row' : 'flex-col'
)}
style={{
transform:
orientation === 'horizontal'
? `translateX(-${currentIndex * 100}%)`
: `translateY(-${currentIndex * 100}%)`,
}}
>
{children}
</div>
</div>
);
}
interface CarouselItemProps {
className?: string;
children: React.ReactNode;
}
function CarouselItem({ className, children }: CarouselItemProps) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn('min-w-0 shrink-0 grow-0 basis-full', className)}
>
{children}
</div>
);
}
interface CarouselPreviousProps {
className?: string;
}
function CarouselPrevious({ className }: CarouselPreviousProps) {
const { scrollPrev, canScrollPrev, orientation } = useCarousel();
return (
<Button
data-slot="carousel-previous"
variant="outline"
onClick={scrollPrev}
disabled={!canScrollPrev}
className={cn(
'absolute size-10 rounded-full p-0 flex items-center justify-center',
orientation === 'horizontal'
? 'top-1/2 left-2 -translate-y-1/2'
: 'top-2 left-1/2 -translate-x-1/2 -rotate-90',
className
)}
aria-label="Previous slide"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
>
<path d="M15 18l-6-6 6-6" />
</svg>
</Button>
);
}
interface CarouselNextProps {
className?: string;
}
function CarouselNext({ className }: CarouselNextProps) {
const { scrollNext, canScrollNext, orientation } = useCarousel();
return (
<Button
data-slot="carousel-next"
variant="outline"
onClick={scrollNext}
disabled={!canScrollNext}
className={cn(
'absolute size-10 rounded-full p-0 flex items-center justify-center',
orientation === 'horizontal'
? 'top-1/2 right-2 -translate-y-1/2'
: 'bottom-2 left-1/2 -translate-x-1/2 rotate-90',
className
)}
aria-label="Next slide"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
>
<path d="M9 18l6-6-6-6" />
</svg>
</Button>
);
}
export {
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
useCarousel,
};

View File

@@ -0,0 +1,193 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
interface CollapsibleContextValue {
open: boolean
setOpen: (open: boolean) => void
contentId: string
}
const CollapsibleContext = React.createContext<CollapsibleContextValue | null>(null)
function useCollapsible() {
const context = React.useContext(CollapsibleContext)
if (!context) {
throw new Error("useCollapsible must be used within a Collapsible")
}
return context
}
interface CollapsibleProps extends React.HTMLAttributes<HTMLDivElement> {
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
disabled?: boolean
}
function Collapsible({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
disabled,
className,
...props
}: CollapsibleProps) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen)
const contentId = React.useId()
const isControlled = controlledOpen !== undefined
const open = isControlled ? controlledOpen : uncontrolledOpen
const setOpen = React.useCallback(
(value: boolean) => {
if (disabled) return
if (!isControlled) {
setUncontrolledOpen(value)
}
onOpenChange?.(value)
},
[disabled, isControlled, onOpenChange]
)
return (
<CollapsibleContext.Provider value={{ open, setOpen, contentId }}>
<div
data-slot="collapsible"
data-state={open ? "open" : "closed"}
data-disabled={disabled || undefined}
className={className}
{...props}
>
{children}
</div>
</CollapsibleContext.Provider>
)
}
interface CollapsibleTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
asChild?: boolean
}
function CollapsibleTrigger({
children,
asChild,
className,
...props
}: CollapsibleTriggerProps) {
const { open, setOpen, contentId } = useCollapsible()
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
props.onClick?.(e)
if (!e.defaultPrevented) {
setOpen(!open)
}
}
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement<any>, {
onClick: handleClick,
"aria-expanded": open,
"aria-controls": contentId,
"data-state": open ? "open" : "closed",
"data-slot": "collapsible-trigger",
})
}
return (
<button
type="button"
data-slot="collapsible-trigger"
data-state={open ? "open" : "closed"}
aria-expanded={open}
aria-controls={contentId}
className={className}
onClick={handleClick}
{...props}
>
{children}
</button>
)
}
interface CollapsibleContentProps extends React.HTMLAttributes<HTMLDivElement> {
forceMount?: boolean
}
function CollapsibleContent({
children,
className,
forceMount,
...props
}: CollapsibleContentProps) {
const { open, contentId } = useCollapsible()
const contentRef = React.useRef<HTMLDivElement>(null)
const [height, setHeight] = React.useState<number | undefined>(undefined)
const [isAnimating, setIsAnimating] = React.useState(false)
React.useLayoutEffect(() => {
const content = contentRef.current
if (!content) return
if (open) {
// Opening: measure and animate
setIsAnimating(true)
const contentHeight = content.scrollHeight
setHeight(contentHeight)
const timer = setTimeout(() => {
setIsAnimating(false)
setHeight(undefined)
}, 200) // Match animation duration
return () => clearTimeout(timer)
} else {
// Closing: set current height first, then animate to 0
const contentHeight = content.scrollHeight
setHeight(contentHeight)
setIsAnimating(true)
// Force reflow then set to 0
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setHeight(0)
})
})
const timer = setTimeout(() => {
setIsAnimating(false)
}, 200)
return () => clearTimeout(timer)
}
}, [open])
if (!open && !isAnimating && !forceMount) {
return null
}
return (
<div
ref={contentRef}
id={contentId}
data-slot="collapsible-content"
data-state={open ? "open" : "closed"}
hidden={!open && !isAnimating && !forceMount}
className={cn(
"overflow-hidden transition-[height] duration-200 ease-out",
className
)}
style={{
height: isAnimating ? height : open ? "auto" : 0,
}}
{...props}
>
{children}
</div>
)
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }

421
components/ui/command.tsx Normal file
View File

@@ -0,0 +1,421 @@
"use client"
import * as React from "react"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
interface CommandContextValue {
search: string
setSearch: (value: string) => void
selectedIndex: number
setSelectedIndex: (index: number) => void
items: React.RefObject<HTMLDivElement[]>
registerItem: (element: HTMLDivElement | null, index: number) => void
filter: (value: string, search: string) => boolean
}
const CommandContext = React.createContext<CommandContextValue | null>(null)
function useCommand() {
const context = React.useContext(CommandContext)
if (!context) {
throw new Error("useCommand must be used within a Command")
}
return context
}
interface CommandProps extends React.HTMLAttributes<HTMLDivElement> {
filter?: (value: string, search: string) => boolean
shouldFilter?: boolean
}
function Command({
className,
children,
filter,
shouldFilter = true,
...props
}: CommandProps) {
const [search, setSearch] = React.useState("")
const [selectedIndex, setSelectedIndex] = React.useState(0)
const items = React.useRef<HTMLDivElement[]>([])
const defaultFilter = React.useCallback((value: string, search: string) => {
if (!shouldFilter) return true
if (search.length === 0) return true
return value.toLowerCase().includes(search.toLowerCase())
}, [shouldFilter])
const registerItem = React.useCallback((element: HTMLDivElement | null, index: number) => {
if (element) {
items.current[index] = element
}
}, [])
const handleKeyDown = React.useCallback((e: React.KeyboardEvent) => {
const visibleItems = items.current.filter((item) => item && !item.hidden)
switch (e.key) {
case "ArrowDown":
e.preventDefault()
setSelectedIndex((prev) => {
const next = prev + 1
return next >= visibleItems.length ? 0 : next
})
break
case "ArrowUp":
e.preventDefault()
setSelectedIndex((prev) => {
const next = prev - 1
return next < 0 ? visibleItems.length - 1 : next
})
break
case "Enter":
e.preventDefault()
const selectedItem = visibleItems[selectedIndex]
if (selectedItem) {
selectedItem.click()
}
break
case "Home":
e.preventDefault()
setSelectedIndex(0)
break
case "End":
e.preventDefault()
setSelectedIndex(visibleItems.length - 1)
break
}
}, [selectedIndex])
React.useEffect(() => {
setSelectedIndex(0)
}, [search])
return (
<CommandContext.Provider
value={{
search,
setSearch,
selectedIndex,
setSelectedIndex,
items,
registerItem,
filter: filter || defaultFilter,
}}
>
<div
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md border border-border",
className
)}
onKeyDown={handleKeyDown}
{...props}
>
{children}
</div>
</CommandContext.Provider>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = false,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0 bg-transparent border-none shadow-none max-w-[450px]", className)}
showCloseButton={showCloseButton}
>
<Command className="rounded-lg border shadow-md w-full [&_[data-slot=command-input-wrapper]]:h-12 [&_[data-slot=command-input]]:h-12 [&_[data-slot=command-item]]:px-2 [&_[data-slot=command-item]]:py-3 [&_svg]:h-5 [&_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.InputHTMLAttributes<HTMLInputElement>) {
const { search, setSearch } = useCommand()
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b border-border px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<input
data-slot="command-input"
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
data-slot="command-list"
role="listbox"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
}
function CommandEmpty({
className,
children,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
const { search, items } = useCommand()
const [isEmpty, setIsEmpty] = React.useState(false)
React.useEffect(() => {
const checkEmpty = () => {
const visibleItems = search.length === 0
? items.current.filter((item) => item)
: items.current.filter((item) => item && !item.hidden)
setIsEmpty(search.length > 0 && visibleItems.length === 0)
}
// Use a small delay to let items update their visibility
const timeout = setTimeout(checkEmpty, 10)
return () => clearTimeout(timeout)
}, [search, items])
if (!isEmpty) return null
return (
<div
data-slot="command-empty"
className={cn("py-6 text-center text-sm", className)}
{...props}
>
{children || "No results found."}
</div>
)
}
interface CommandGroupProps extends React.HTMLAttributes<HTMLDivElement> {
heading?: React.ReactNode
}
function CommandGroup({
className,
heading,
children,
...props
}: CommandGroupProps) {
const groupRef = React.useRef<HTMLDivElement>(null)
const { search } = useCommand()
const [hasVisibleItems, setHasVisibleItems] = React.useState(true)
React.useEffect(() => {
if (search.length === 0) {
setHasVisibleItems(true)
return
}
const checkVisibility = () => {
if (groupRef.current) {
const items = groupRef.current.querySelectorAll('[data-slot="command-item"]')
const visibleItems = Array.from(items).filter(
(item) => !(item as HTMLElement).hidden
)
setHasVisibleItems(visibleItems.length > 0)
}
}
const timeout = setTimeout(checkVisibility, 10)
return () => clearTimeout(timeout)
}, [search])
return (
<div
ref={groupRef}
data-slot="command-group"
role="group"
hidden={!hasVisibleItems}
className={cn(
"text-foreground overflow-hidden p-1",
className
)}
{...props}
>
{heading && (
<div className="text-muted-foreground px-2 py-1.5 text-xs font-medium">
{heading}
</div>
)}
{children}
</div>
)
}
function CommandSeparator({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
data-slot="command-separator"
role="separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
)
}
interface CommandItemProps extends React.HTMLAttributes<HTMLDivElement> {
disabled?: boolean
value?: string
onSelect?: (value: string) => void
keywords?: string[]
}
const itemIndexCounter = { current: 0 }
function getTextFromChildren(children: React.ReactNode): string {
if (typeof children === "string") return children
if (typeof children === "number") return String(children)
if (Array.isArray(children)) return children.map(getTextFromChildren).join(" ")
if (React.isValidElement(children) && children.props.children) {
return getTextFromChildren(children.props.children)
}
return ""
}
function CommandItem({
className,
disabled,
value,
onSelect,
keywords = [],
children,
...props
}: CommandItemProps) {
const { search, selectedIndex, setSelectedIndex, registerItem, filter } = useCommand()
const ref = React.useRef<HTMLDivElement>(null)
const indexRef = React.useRef<number>(-1)
React.useLayoutEffect(() => {
indexRef.current = itemIndexCounter.current++
return () => {
itemIndexCounter.current = Math.max(0, itemIndexCounter.current - 1)
}
}, [])
React.useEffect(() => {
registerItem(ref.current, indexRef.current)
}, [registerItem])
const searchableText = value || getTextFromChildren(children)
const allSearchableText = [searchableText, ...keywords].join(" ")
const isVisible = search.length === 0 ? true : filter(allSearchableText, search)
const isSelected = selectedIndex === indexRef.current && isVisible
const handleSelect = () => {
if (disabled) return
onSelect?.(searchableText)
}
const handleMouseEnter = () => {
if (!disabled) {
setSelectedIndex(indexRef.current)
}
}
return (
<div
ref={ref}
data-slot="command-item"
role="option"
aria-selected={isSelected}
aria-disabled={disabled}
data-selected={isSelected}
data-disabled={disabled}
hidden={!isVisible}
tabIndex={disabled ? -1 : 0}
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground",
"[&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none",
"data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
onClick={handleSelect}
onMouseEnter={handleMouseEnter}
{...props}
>
{children}
</div>
)
}
function CommandShortcut({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

274
components/ui/dialog.tsx Normal file
View File

@@ -0,0 +1,274 @@
import React, { useState, useCallback, useContext, createContext } from 'react';
import { createPortal } from 'react-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
interface DialogContextType {
open: boolean;
setOpen: (open: boolean) => void;
}
const DialogContext = createContext<DialogContextType | undefined>(undefined);
function useDialog() {
const context = useContext(DialogContext);
if (!context) {
throw new Error('Dialog components must be used within a Dialog');
}
return context;
}
interface DialogProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
children: React.ReactNode;
}
function Dialog({ open: controlledOpen, onOpenChange, children }: DialogProps) {
const [internalOpen, setInternalOpen] = useState(false);
const isControlled = controlledOpen !== undefined;
const open = isControlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(newOpen: boolean) => {
if (!isControlled) {
setInternalOpen(newOpen);
}
onOpenChange?.(newOpen);
},
[isControlled, onOpenChange]
);
return (
<DialogContext.Provider value={{ open, setOpen }}>
{children}
</DialogContext.Provider>
);
}
function DialogTrigger({
children,
asChild,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }) {
const { setOpen } = useDialog();
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement, {
...props,
onClick: (e: React.MouseEvent) => {
setOpen(true);
children.props.onClick?.(e);
},
});
}
return (
<button
{...props}
onClick={(e) => {
setOpen(true);
props.onClick?.(e);
}}
>
{children}
</button>
);
}
function DialogPortal({ children }: { children: React.ReactNode }) {
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) return null;
return createPortal(children, document.body);
}
function DialogClose({
children,
asChild,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }) {
const { setOpen } = useDialog();
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement, {
...props,
onClick: (e: React.MouseEvent) => {
setOpen(false);
children.props.onClick?.(e);
},
});
}
return (
<button
{...props}
onClick={(e) => {
setOpen(false);
props.onClick?.(e);
}}
>
{children}
</button>
);
}
interface DialogOverlayProps extends React.HTMLAttributes<HTMLDivElement> {}
function DialogOverlay({ className, onClick, ...props }: DialogOverlayProps) {
const { setOpen } = useDialog();
return (
<motion.div
data-slot="dialog-overlay"
className={cn('fixed inset-0 z-50 bg-black/50', className)}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={(e) => {
setOpen(false);
onClick?.(e as any);
}}
{...props}
/>
);
}
interface DialogContentProps extends React.HTMLAttributes<HTMLDivElement> {
showCloseButton?: boolean;
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: DialogContentProps) {
const { open } = useDialog();
return (
<DialogPortal>
<AnimatePresence>
{open && (
<>
<DialogOverlay />
<motion.div
data-slot="dialog-content"
className={cn(
'bg-background fixed top-1/2 left-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg border border-border p-6 shadow-lg',
className
)}
initial={{ opacity: 0, scale: 0.95, y: 0 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 0 }}
transition={{ type: 'spring', stiffness: 300, damping: 30 }}
{...props}
>
{children}
{showCloseButton && (
<DialogClose
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none"
aria-label="Close"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
>
<path d="M18 6l-12 12M6 6l12 12" />
</svg>
</DialogClose>
)}
</motion.div>
</>
)}
</AnimatePresence>
</DialogPortal>
);
}
function DialogHeader({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
data-slot="dialog-header"
className={cn(
'flex flex-col gap-2 text-center sm:text-left',
className
)}
{...props}
/>
);
}
function DialogFooter({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
data-slot="dialog-footer"
className={cn(
'flex flex-col-reverse gap-2 sm:flex-row sm:justify-end',
className
)}
{...props}
/>
);
}
function DialogTitle({
className,
...props
}: React.HTMLAttributes<HTMLHeadingElement>) {
return (
<h2
data-slot="dialog-title"
className={cn('text-lg leading-none font-semibold', className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.HTMLAttributes<HTMLParagraphElement>) {
return (
<p
data-slot="dialog-description"
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
AnimatePresence,
};

View File

@@ -0,0 +1,616 @@
"use client"
import * as React from "react"
import { createPortal } from "react-dom"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
interface DropdownMenuContextValue {
open: boolean
setOpen: (open: boolean) => void
triggerRef: React.RefObject<HTMLButtonElement | null>
}
const DropdownMenuContext = React.createContext<DropdownMenuContextValue | null>(null)
function useDropdownMenu() {
const context = React.useContext(DropdownMenuContext)
if (!context) {
throw new Error("useDropdownMenu must be used within a DropdownMenu")
}
return context
}
interface DropdownMenuProps {
children: React.ReactNode
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
}
function DropdownMenu({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
}: DropdownMenuProps) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen)
const triggerRef = React.useRef<HTMLButtonElement>(null)
const isControlled = controlledOpen !== undefined
const open = isControlled ? controlledOpen : uncontrolledOpen
const setOpen = React.useCallback((value: boolean) => {
if (!isControlled) {
setUncontrolledOpen(value)
}
onOpenChange?.(value)
}, [isControlled, onOpenChange])
return (
<DropdownMenuContext.Provider value={{ open, setOpen, triggerRef }}>
{children}
</DropdownMenuContext.Provider>
)
}
function DropdownMenuTrigger({
className,
children,
asChild,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }) {
const { open, setOpen, triggerRef } = useDropdownMenu()
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
setOpen(!open)
props.onClick?.(e)
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (e.key === "Enter" || e.key === " " || e.key === "ArrowDown") {
e.preventDefault()
setOpen(true)
}
props.onKeyDown?.(e)
}
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement<any>, {
ref: triggerRef,
onClick: handleClick,
onKeyDown: handleKeyDown,
"aria-expanded": open,
"aria-haspopup": "menu",
"data-state": open ? "open" : "closed",
})
}
return (
<button
ref={triggerRef}
type="button"
data-slot="dropdown-menu-trigger"
aria-expanded={open}
aria-haspopup="menu"
data-state={open ? "open" : "closed"}
className={cn("relative", className)}
onClick={handleClick}
onKeyDown={handleKeyDown}
{...props}
>
{children}
</button>
)
}
function DropdownMenuPortal({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
interface DropdownMenuContentProps extends React.HTMLAttributes<HTMLDivElement> {
sideOffset?: number
align?: "start" | "center" | "end"
side?: "top" | "right" | "bottom" | "left"
}
function DropdownMenuContent({
className,
sideOffset = 4,
align = "start",
side = "bottom",
children,
...props
}: DropdownMenuContentProps) {
const { open, setOpen, triggerRef } = useDropdownMenu()
const contentRef = React.useRef<HTMLDivElement>(null)
const [position, setPosition] = React.useState({ top: 0, left: 0 })
const [mounted, setMounted] = React.useState(false)
React.useEffect(() => {
setMounted(true)
}, [])
React.useLayoutEffect(() => {
if (!open || !triggerRef.current || !contentRef.current) return
const trigger = triggerRef.current.getBoundingClientRect()
const content = contentRef.current.getBoundingClientRect()
let top = 0
let left = 0
// Calculate position based on side
switch (side) {
case "top":
top = trigger.top - content.height - sideOffset
break
case "bottom":
top = trigger.bottom + sideOffset
break
case "left":
left = trigger.left - content.width - sideOffset
top = trigger.top
break
case "right":
left = trigger.right + sideOffset
top = trigger.top
break
}
// Calculate alignment for top/bottom
if (side === "top" || side === "bottom") {
switch (align) {
case "start":
left = trigger.left
break
case "center":
left = trigger.left + (trigger.width - content.width) / 2
break
case "end":
left = trigger.right - content.width
break
}
}
// Calculate alignment for left/right
if (side === "left" || side === "right") {
switch (align) {
case "start":
top = trigger.top
break
case "center":
top = trigger.top + (trigger.height - content.height) / 2
break
case "end":
top = trigger.bottom - content.height
break
}
}
setPosition({ top, left })
}, [open, side, align, sideOffset, triggerRef])
React.useEffect(() => {
if (!open) return
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Node
if (
contentRef.current &&
!contentRef.current.contains(target) &&
triggerRef.current &&
!triggerRef.current.contains(target)
) {
setOpen(false)
}
}
const handleEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setOpen(false)
triggerRef.current?.focus()
}
}
document.addEventListener("mousedown", handleClickOutside)
document.addEventListener("keydown", handleEscape)
return () => {
document.removeEventListener("mousedown", handleClickOutside)
document.removeEventListener("keydown", handleEscape)
}
}, [open, setOpen, triggerRef])
if (!open || !mounted) return null
const slideClasses = {
top: "slide-in-from-bottom-2",
bottom: "slide-in-from-top-2",
left: "slide-in-from-right-2",
right: "slide-in-from-left-2",
}
return createPortal(
<div
ref={contentRef}
data-slot="dropdown-menu-content"
data-state={open ? "open" : "closed"}
role="menu"
className={cn(
"fixed z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"animate-in fade-in-0 zoom-in-95",
slideClasses[side],
className
)}
style={{
top: position.top,
left: position.left,
}}
{...props}
>
{children}
</div>,
document.body
)
}
function DropdownMenuGroup({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
data-slot="dropdown-menu-group"
role="group"
className={className}
{...props}
/>
)
}
interface DropdownMenuItemProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
inset?: boolean
variant?: "default" | "destructive"
asChild?: boolean
}
function DropdownMenuItem({
className,
inset,
variant = "default",
children,
asChild,
...props
}: DropdownMenuItemProps) {
const { setOpen } = useDropdownMenu()
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
props.onClick?.(e)
if (!e.defaultPrevented) {
setOpen(false)
}
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault()
handleClick(e as unknown as React.MouseEvent<HTMLButtonElement>)
}
props.onKeyDown?.(e)
}
const itemClasses = cn(
"focus:bg-accent focus:text-accent-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
variant === "destructive" && "text-destructive focus:bg-destructive/10 focus:text-destructive dark:focus:bg-destructive/20",
inset && "pl-8",
className
)
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement<any>, {
className: itemClasses,
role: "menuitem",
tabIndex: -1,
onClick: handleClick,
onKeyDown: handleKeyDown,
})
}
return (
<button
type="button"
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
role="menuitem"
tabIndex={-1}
className={itemClasses}
onClick={handleClick}
onKeyDown={handleKeyDown}
{...props}
>
{children}
</button>
)
}
interface DropdownMenuCheckboxItemProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "checked"> {
checked?: boolean
onCheckedChange?: (checked: boolean) => void
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
onCheckedChange,
...props
}: DropdownMenuCheckboxItemProps) {
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
onCheckedChange?.(!checked)
props.onClick?.(e)
}
return (
<button
type="button"
data-slot="dropdown-menu-checkbox-item"
role="menuitemcheckbox"
aria-checked={checked}
tabIndex={-1}
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-none select-none",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
onClick={handleClick}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
{checked && <CheckIcon className="size-4" />}
</span>
{children}
</button>
)
}
interface DropdownMenuRadioGroupProps extends React.HTMLAttributes<HTMLDivElement> {
value?: string
onValueChange?: (value: string) => void
}
const RadioGroupContext = React.createContext<{
value?: string
onValueChange?: (value: string) => void
} | null>(null)
function DropdownMenuRadioGroup({
value,
onValueChange,
children,
...props
}: DropdownMenuRadioGroupProps) {
return (
<RadioGroupContext.Provider value={{ value, onValueChange }}>
<div
data-slot="dropdown-menu-radio-group"
role="group"
{...props}
>
{children}
</div>
</RadioGroupContext.Provider>
)
}
interface DropdownMenuRadioItemProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
value: string
}
function DropdownMenuRadioItem({
className,
children,
value,
...props
}: DropdownMenuRadioItemProps) {
const context = React.useContext(RadioGroupContext)
const checked = context?.value === value
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
context?.onValueChange?.(value)
props.onClick?.(e)
}
return (
<button
type="button"
data-slot="dropdown-menu-radio-item"
role="menuitemradio"
aria-checked={checked}
tabIndex={-1}
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-none select-none",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
onClick={handleClick}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
{checked && <CircleIcon className="size-2 fill-current" />}
</span>
{children}
</button>
)
}
interface DropdownMenuLabelProps extends React.HTMLAttributes<HTMLDivElement> {
inset?: boolean
}
function DropdownMenuLabel({
className,
inset,
...props
}: DropdownMenuLabelProps) {
return (
<div
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium",
inset && "pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
data-slot="dropdown-menu-separator"
role="separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
interface SubMenuContextValue {
open: boolean
setOpen: (open: boolean) => void
}
const SubMenuContext = React.createContext<SubMenuContextValue | null>(null)
function DropdownMenuSub({ children }: { children: React.ReactNode }) {
const [open, setOpen] = React.useState(false)
return (
<SubMenuContext.Provider value={{ open, setOpen }}>
<div data-slot="dropdown-menu-sub" className="relative">
{children}
</div>
</SubMenuContext.Provider>
)
}
interface DropdownMenuSubTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
inset?: boolean
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: DropdownMenuSubTriggerProps) {
const context = React.useContext(SubMenuContext)
const handleMouseEnter = () => {
context?.setOpen(true)
}
const handleMouseLeave = () => {
context?.setOpen(false)
}
return (
<button
type="button"
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
data-state={context?.open ? "open" : "closed"}
role="menuitem"
aria-haspopup="menu"
aria-expanded={context?.open}
tabIndex={-1}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
"[&_svg:not([class*='text-'])]:text-muted-foreground flex w-full cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none",
inset && "pl-8",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</button>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
const context = React.useContext(SubMenuContext)
if (!context?.open) return null
return (
<div
data-slot="dropdown-menu-sub-content"
data-state={context.open ? "open" : "closed"}
role="menu"
className={cn(
"absolute left-full top-0 z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg",
"animate-in fade-in-0 zoom-in-95 slide-in-from-left-2",
className
)}
onMouseEnter={() => context.setOpen(true)}
onMouseLeave={() => context.setOpen(false)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

105
components/ui/empty.tsx Normal file
View File

@@ -0,0 +1,105 @@
import React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
function Empty({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty"
className={cn(
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12",
className
)}
{...props}
/>
)
}
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-header"
className={cn(
"flex max-w-sm flex-col items-center gap-2 text-center",
className
)}
{...props}
/>
)
}
const emptyMediaVariants = cva(
"flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-transparent",
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
},
},
defaultVariants: {
variant: "default",
},
}
)
function EmptyMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
return (
<div
data-slot="empty-icon"
data-variant={variant}
className={cn(emptyMediaVariants({ variant, className }))}
{...props}
/>
)
}
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-title"
className={cn("text-lg font-medium tracking-tight", className)}
{...props}
/>
)
}
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<div
data-slot="empty-description"
className={cn(
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-content"
className={cn(
"flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance",
className
)}
{...props}
/>
)
}
export {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
EmptyMedia,
}

View File

@@ -0,0 +1,260 @@
"use client"
import * as React from "react"
import { createPortal } from "react-dom"
import { cn } from "@/lib/utils"
interface HoverCardContextValue {
open: boolean
setOpen: (open: boolean) => void
triggerRef: React.RefObject<HTMLElement | null>
cancelClose: () => void
}
const HoverCardContext = React.createContext<HoverCardContextValue | null>(null)
function useHoverCard() {
const context = React.useContext(HoverCardContext)
if (!context) {
throw new Error("useHoverCard must be used within a HoverCard")
}
return context
}
interface HoverCardProps {
children: React.ReactNode
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
openDelay?: number
closeDelay?: number
}
function HoverCard({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
openDelay = 700,
closeDelay = 300,
}: HoverCardProps) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen)
const triggerRef = React.useRef<HTMLElement>(null)
const openTimeoutRef = React.useRef<NodeJS.Timeout | null>(null)
const closeTimeoutRef = React.useRef<NodeJS.Timeout | null>(null)
const isControlled = controlledOpen !== undefined
const open = isControlled ? controlledOpen : uncontrolledOpen
const setOpen = React.useCallback(
(value: boolean) => {
if (openTimeoutRef.current) {
clearTimeout(openTimeoutRef.current)
openTimeoutRef.current = null
}
if (closeTimeoutRef.current) {
clearTimeout(closeTimeoutRef.current)
closeTimeoutRef.current = null
}
if (value) {
openTimeoutRef.current = setTimeout(() => {
if (!isControlled) {
setUncontrolledOpen(true)
}
onOpenChange?.(true)
}, openDelay)
} else {
closeTimeoutRef.current = setTimeout(() => {
if (!isControlled) {
setUncontrolledOpen(false)
}
onOpenChange?.(false)
}, closeDelay)
}
},
[isControlled, onOpenChange, openDelay, closeDelay]
)
const cancelClose = React.useCallback(() => {
if (closeTimeoutRef.current) {
clearTimeout(closeTimeoutRef.current)
closeTimeoutRef.current = null
}
}, [])
React.useEffect(() => {
return () => {
if (openTimeoutRef.current) clearTimeout(openTimeoutRef.current)
if (closeTimeoutRef.current) clearTimeout(closeTimeoutRef.current)
}
}, [])
return (
<HoverCardContext.Provider value={{ open, setOpen, triggerRef, cancelClose }}>
{children}
</HoverCardContext.Provider>
)
}
interface HoverCardTriggerProps extends React.HTMLAttributes<HTMLSpanElement> {
asChild?: boolean
}
function HoverCardTrigger({
children,
asChild,
...props
}: HoverCardTriggerProps) {
const { setOpen, triggerRef } = useHoverCard()
const handleMouseEnter = () => {
setOpen(true)
}
const handleMouseLeave = () => {
setOpen(false)
}
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement<any>, {
ref: triggerRef,
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave,
"data-slot": "hover-card-trigger",
})
}
return (
<span
ref={triggerRef as React.RefObject<HTMLSpanElement>}
data-slot="hover-card-trigger"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
{children}
</span>
)
}
interface HoverCardContentProps extends React.HTMLAttributes<HTMLDivElement> {
side?: "top" | "right" | "bottom" | "left"
sideOffset?: number
align?: "start" | "center" | "end"
}
function HoverCardContent({
className,
side = "bottom",
sideOffset = 4,
align = "center",
children,
...props
}: HoverCardContentProps) {
const { open, setOpen, triggerRef, cancelClose } = useHoverCard()
const [position, setPosition] = React.useState({ top: 0, left: 0 })
const [mounted, setMounted] = React.useState(false)
const contentRef = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
setMounted(true)
}, [])
React.useLayoutEffect(() => {
if (!open || !triggerRef.current || !contentRef.current) return
const trigger = triggerRef.current.getBoundingClientRect()
const content = contentRef.current.getBoundingClientRect()
let top = 0
let left = 0
// Calculate position based on side
switch (side) {
case "top":
top = trigger.top - content.height - sideOffset
break
case "bottom":
top = trigger.bottom + sideOffset
break
case "left":
left = trigger.left - content.width - sideOffset
top = trigger.top + (trigger.height - content.height) / 2
break
case "right":
left = trigger.right + sideOffset
top = trigger.top + (trigger.height - content.height) / 2
break
}
// Calculate alignment for top/bottom
if (side === "top" || side === "bottom") {
switch (align) {
case "start":
left = trigger.left
break
case "center":
left = trigger.left + (trigger.width - content.width) / 2
break
case "end":
left = trigger.right - content.width
break
}
}
// Calculate alignment for left/right
if (side === "left" || side === "right") {
switch (align) {
case "start":
top = trigger.top
break
case "center":
top = trigger.top + (trigger.height - content.height) / 2
break
case "end":
top = trigger.bottom - content.height
break
}
}
setPosition({ top, left })
}, [open, side, align, sideOffset, triggerRef])
if (!open || !mounted) return null
const slideClasses = {
top: "slide-in-from-bottom-2",
bottom: "slide-in-from-top-2",
left: "slide-in-from-right-2",
right: "slide-in-from-left-2",
}
return createPortal(
<div
ref={contentRef}
data-slot="hover-card-content"
data-state={open ? "open" : "closed"}
data-side={side}
className={cn(
"fixed z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none",
"animate-in fade-in-0 zoom-in-95",
slideClasses[side],
className
)}
style={{
top: position.top,
left: position.left,
}}
onMouseEnter={cancelClose}
onMouseLeave={() => setOpen(false)}
{...props}
>
{children}
</div>,
document.body
)
}
export { HoverCard, HoverCardTrigger, HoverCardContent }

View File

@@ -0,0 +1,180 @@
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
interface InputGroupProps extends React.ComponentProps<"div"> {
layout?: "inline" | "stacked"
}
function InputGroup({ className, layout, ...props }: InputGroupProps) {
// Detect layout from children if not explicitly set
const hasBlockAddon = React.Children.toArray(props.children).some(
(child) =>
React.isValidElement(child) &&
((child.props as any)?.align === "block-end" ||
(child.props as any)?.align === "block-start")
)
const isStacked = layout === "stacked" || hasBlockAddon
return (
<div
data-slot="input-group"
data-layout={isStacked ? "stacked" : "inline"}
role="group"
className={cn(
"group/input-group border-input dark:bg-input/30 relative flex w-full rounded-md border shadow-xs transition-[color,box-shadow] outline-none",
isStacked ? "h-auto flex-col" : "h-9 min-w-0 items-center",
// Focus state.
"focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",
// Error state.
"has-[[aria-invalid=true]]:ring-destructive/20 has-[[aria-invalid=true]]:border-destructive dark:has-[[aria-invalid=true]]:ring-destructive/40",
className
)}
{...props}
/>
)
}
const inputGroupAddonVariants = cva(
"text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",
{
variants: {
align: {
"inline-start":
"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]",
"inline-end":
"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]",
"block-start":
"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5",
"block-end":
"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5",
},
},
defaultVariants: {
align: "inline-start",
},
}
)
function InputGroupAddon({
className,
align = "inline-start",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest("button")) {
return
}
e.currentTarget.parentElement?.querySelector("input")?.focus()
}}
{...props}
/>
)
}
InputGroupAddon.displayName = "InputGroupAddon"
const inputGroupButtonVariants = cva(
"text-sm shadow-none flex gap-2 items-center",
{
variants: {
size: {
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
sm: "h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5",
"icon-xs":
"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0",
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
},
},
defaultVariants: {
size: "xs",
},
}
)
function InputGroupButton({
className,
type = "button",
variant = "ghost",
size = "xs",
...props
}: Omit<React.ComponentProps<typeof Button>, "size"> &
VariantProps<typeof inputGroupButtonVariants>) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
)
}
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"text-muted-foreground flex items-center gap-2 text-sm [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function InputGroupInput({
className,
...props
}: React.ComponentProps<"input">) {
return (
<Input
data-slot="input-group-control"
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
className
)}
{...props}
/>
)
}
function InputGroupTextarea({
className,
...props
}: React.ComponentProps<"textarea">) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
className
)}
{...props}
/>
)
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
}

View File

@@ -0,0 +1,86 @@
import React from 'react';
import { OTPInput, OTPInputContext } from 'input-otp';
import { cn } from '@/lib/utils';
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string;
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn(
'flex items-center gap-2 has-disabled:opacity-50',
containerClassName
)}
className={cn('disabled:cursor-not-allowed', className)}
{...props}
/>
);
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="input-otp-group"
className={cn('flex items-center', className)}
{...props}
/>
);
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<'div'> & {
index: number;
}) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
'data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r border-border text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l first:border-border last:rounded-r-md last:border-border data-[active=true]:z-10 data-[active=true]:ring-[3px]',
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
</div>
);
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

21
components/ui/input.tsx Normal file
View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-background px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

213
components/ui/item.tsx Normal file
View File

@@ -0,0 +1,213 @@
import React from 'react';
// Utility function to combine classNames
function cn(...classes: (string | undefined | null | false)[]): string {
return classes.filter(Boolean).join(' ');
}
// Item variants helper
function getItemVariants(
variant: 'default' | 'outline' | 'muted',
size: 'default' | 'sm'
): string {
const baseStyles =
'group/item flex items-center border border-transparent text-sm rounded-md transition-colors [a]:hover:bg-accent/50 [a]:transition-colors duration-100 flex-wrap outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]';
const variantStyles = {
default: 'bg-transparent',
outline: 'border-border',
muted: 'bg-muted/50',
};
const sizeStyles = {
default: 'p-4 gap-4',
sm: 'py-3 px-4 gap-2.5',
};
return cn(baseStyles, variantStyles[variant], sizeStyles[size]);
}
// Item media variants helper
function getItemMediaVariants(variant: 'default' | 'icon' | 'image'): string {
const baseStyles =
'flex shrink-0 items-center justify-center gap-2 group-has-[[data-slot=item-description]]/item:self-start [&_svg]:pointer-events-none group-has-[[data-slot=item-description]]/item:translate-y-0.5';
const variantStyles = {
default: 'bg-transparent',
icon: "size-8 border border-border rounded-sm bg-muted [&_svg:not([class*='size-'])]:size-4",
image:
'size-10 rounded-sm overflow-hidden [&_img]:size-full [&_img]:object-cover',
};
return cn(baseStyles, variantStyles[variant]);
}
interface ItemGroupProps extends React.ComponentProps<'div'> {}
function ItemGroup({ className, ...props }: ItemGroupProps) {
return (
<div
role="list"
data-slot="item-group"
className={cn('group/item-group flex flex-col', className)}
{...props}
/>
);
}
interface ItemSeparatorProps extends React.ComponentProps<'div'> {}
function ItemSeparator({ className, ...props }: ItemSeparatorProps) {
return (
<div
data-slot="item-separator"
className={cn('my-0 border-t border-border', className)}
{...props}
/>
);
}
interface ItemProps extends React.ComponentProps<'div'> {
variant?: 'default' | 'outline' | 'muted';
size?: 'default' | 'sm';
asChild?: boolean;
}
function Item({
className,
variant = 'default',
size = 'default',
asChild = false,
...props
}: ItemProps) {
const Comp = asChild ? 'div' : 'div';
return (
<Comp
data-slot="item"
data-variant={variant}
data-size={size}
className={cn(getItemVariants(variant, size), className)}
{...props}
/>
);
}
interface ItemMediaProps extends React.ComponentProps<'div'> {
variant?: 'default' | 'icon' | 'image';
}
function ItemMedia({
className,
variant = 'default',
...props
}: ItemMediaProps) {
return (
<div
data-slot="item-media"
data-variant={variant}
className={cn(getItemMediaVariants(variant), className)}
{...props}
/>
);
}
interface ItemContentProps extends React.ComponentProps<'div'> {}
function ItemContent({ className, ...props }: ItemContentProps) {
return (
<div
data-slot="item-content"
className={cn(
'flex flex-1 flex-col gap-1 [&+[data-slot=item-content]]:flex-none',
className
)}
{...props}
/>
);
}
interface ItemTitleProps extends React.ComponentProps<'div'> {}
function ItemTitle({ className, ...props }: ItemTitleProps) {
return (
<div
data-slot="item-title"
className={cn(
'flex w-fit items-center gap-2 text-sm leading-snug font-medium',
className
)}
{...props}
/>
);
}
interface ItemDescriptionProps extends React.ComponentProps<'p'> {}
function ItemDescription({ className, ...props }: ItemDescriptionProps) {
return (
<p
data-slot="item-description"
className={cn(
'text-muted-foreground line-clamp-2 text-sm leading-normal font-normal text-balance',
'[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4',
className
)}
{...props}
/>
);
}
interface ItemActionsProps extends React.ComponentProps<'div'> {}
function ItemActions({ className, ...props }: ItemActionsProps) {
return (
<div
data-slot="item-actions"
className={cn('flex items-center gap-2', className)}
{...props}
/>
);
}
interface ItemHeaderProps extends React.ComponentProps<'div'> {}
function ItemHeader({ className, ...props }: ItemHeaderProps) {
return (
<div
data-slot="item-header"
className={cn(
'flex basis-full items-center justify-between gap-2',
className
)}
{...props}
/>
);
}
interface ItemFooterProps extends React.ComponentProps<'div'> {}
function ItemFooter({ className, ...props }: ItemFooterProps) {
return (
<div
data-slot="item-footer"
className={cn(
'flex basis-full items-center justify-between gap-2',
className
)}
{...props}
/>
);
}
export {
Item,
ItemMedia,
ItemContent,
ItemActions,
ItemGroup,
ItemSeparator,
ItemTitle,
ItemDescription,
ItemHeader,
ItemFooter,
};

23
components/ui/label.tsx Normal file
View File

@@ -0,0 +1,23 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<"label">) {
return (
<label
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,127 @@
import * as React from "react"
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { buttonVariants, type Button } from "@/components/ui/button"
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
)
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />
}
type PaginationLinkProps = {
isActive?: boolean
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
{...props}
>
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
)
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
{...props}
>
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
)
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
)
}
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}

View File

@@ -0,0 +1,44 @@
import React from 'react';
// Utility function to combine classNames
function cn(...classes: (string | undefined | null | false)[]): string {
return classes.filter(Boolean).join(' ');
}
interface ProgressProps extends React.ComponentProps<'div'> {
value?: number;
max?: number;
}
function Progress({
className,
value = 0,
max = 100,
...props
}: ProgressProps) {
const percentage = Math.min(Math.max((value / max) * 100, 0), 100);
return (
<div
data-slot="progress"
className={cn(
'bg-primary/20 relative h-2 w-full overflow-hidden rounded-full',
className
)}
role="progressbar"
aria-valuemin={0}
aria-valuemax={max}
aria-valuenow={value}
{...props}
>
<div
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - percentage}%)` }}
/>
</div>
);
}
export { Progress };
export type { ProgressProps };

View File

@@ -0,0 +1,241 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
interface ScrollAreaProps extends React.HTMLAttributes<HTMLDivElement> {
orientation?: "vertical" | "horizontal" | "both"
}
function ScrollArea({
className,
children,
orientation = "vertical",
...props
}: ScrollAreaProps) {
const viewportRef = React.useRef<HTMLDivElement>(null)
const [showVerticalScrollbar, setShowVerticalScrollbar] = React.useState(false)
const [showHorizontalScrollbar, setShowHorizontalScrollbar] = React.useState(false)
const [scrollTop, setScrollTop] = React.useState(0)
const [scrollLeft, setScrollLeft] = React.useState(0)
const [viewportHeight, setViewportHeight] = React.useState(0)
const [viewportWidth, setViewportWidth] = React.useState(0)
const [contentHeight, setContentHeight] = React.useState(0)
const [contentWidth, setContentWidth] = React.useState(0)
React.useEffect(() => {
const viewport = viewportRef.current
if (!viewport) return
const updateScrollInfo = () => {
const hasVerticalScroll = viewport.scrollHeight > viewport.clientHeight
const hasHorizontalScroll = viewport.scrollWidth > viewport.clientWidth
setShowVerticalScrollbar(
hasVerticalScroll && (orientation === "vertical" || orientation === "both")
)
setShowHorizontalScrollbar(
hasHorizontalScroll && (orientation === "horizontal" || orientation === "both")
)
setViewportHeight(viewport.clientHeight)
setViewportWidth(viewport.clientWidth)
setContentHeight(viewport.scrollHeight)
setContentWidth(viewport.scrollWidth)
}
const handleScroll = () => {
setScrollTop(viewport.scrollTop)
setScrollLeft(viewport.scrollLeft)
}
updateScrollInfo()
viewport.addEventListener("scroll", handleScroll)
const resizeObserver = new ResizeObserver(updateScrollInfo)
resizeObserver.observe(viewport)
// Also observe children for content changes
const mutationObserver = new MutationObserver(updateScrollInfo)
mutationObserver.observe(viewport, { childList: true, subtree: true })
return () => {
viewport.removeEventListener("scroll", handleScroll)
resizeObserver.disconnect()
mutationObserver.disconnect()
}
}, [orientation])
return (
<div
data-slot="scroll-area"
className={cn("relative overflow-hidden", className)}
{...props}
>
<div
ref={viewportRef}
data-slot="scroll-area-viewport"
className={cn(
"size-full rounded-[inherit] outline-none",
"focus-visible:ring-ring/50 transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1",
orientation === "vertical" && "overflow-y-auto overflow-x-hidden",
orientation === "horizontal" && "overflow-x-auto overflow-y-hidden",
orientation === "both" && "overflow-auto"
)}
tabIndex={0}
>
{children}
</div>
{showVerticalScrollbar && (
<ScrollBar
orientation="vertical"
viewportRef={viewportRef}
scrollPosition={scrollTop}
viewportSize={viewportHeight}
contentSize={contentHeight}
/>
)}
{showHorizontalScrollbar && (
<ScrollBar
orientation="horizontal"
viewportRef={viewportRef}
scrollPosition={scrollLeft}
viewportSize={viewportWidth}
contentSize={contentWidth}
/>
)}
</div>
)
}
interface ScrollBarProps extends React.HTMLAttributes<HTMLDivElement> {
orientation?: "vertical" | "horizontal"
viewportRef?: React.RefObject<HTMLDivElement | null>
scrollPosition?: number
viewportSize?: number
contentSize?: number
}
function ScrollBar({
className,
orientation = "vertical",
viewportRef,
scrollPosition = 0,
viewportSize = 0,
contentSize = 0,
...props
}: ScrollBarProps) {
const [isDragging, setIsDragging] = React.useState(false)
const [isHovered, setIsHovered] = React.useState(false)
const scrollbarRef = React.useRef<HTMLDivElement>(null)
const startPosRef = React.useRef(0)
const startScrollRef = React.useRef(0)
const thumbSize =
contentSize > 0 ? Math.max((viewportSize / contentSize) * 100, 10) : 0
const thumbPosition =
contentSize > viewportSize
? (scrollPosition / (contentSize - viewportSize)) * (100 - thumbSize)
: 0
const handleThumbMouseDown = (e: React.MouseEvent) => {
e.preventDefault()
setIsDragging(true)
startPosRef.current = orientation === "vertical" ? e.clientY : e.clientX
startScrollRef.current = scrollPosition
}
React.useEffect(() => {
if (!isDragging) return
const handleMouseMove = (e: MouseEvent) => {
const viewport = viewportRef?.current
const scrollbar = scrollbarRef.current
if (!viewport || !scrollbar) return
const currentPos = orientation === "vertical" ? e.clientY : e.clientX
const delta = currentPos - startPosRef.current
const scrollbarSize =
orientation === "vertical"
? scrollbar.clientHeight
: scrollbar.clientWidth
const scrollRatio = (contentSize - viewportSize) / (scrollbarSize * (1 - thumbSize / 100))
const newScrollPos = startScrollRef.current + delta * scrollRatio
if (orientation === "vertical") {
viewport.scrollTop = Math.max(0, Math.min(newScrollPos, contentSize - viewportSize))
} else {
viewport.scrollLeft = Math.max(0, Math.min(newScrollPos, contentSize - viewportSize))
}
}
const handleMouseUp = () => {
setIsDragging(false)
}
document.addEventListener("mousemove", handleMouseMove)
document.addEventListener("mouseup", handleMouseUp)
return () => {
document.removeEventListener("mousemove", handleMouseMove)
document.removeEventListener("mouseup", handleMouseUp)
}
}, [isDragging, orientation, viewportRef, contentSize, viewportSize, thumbSize])
const handleTrackClick = (e: React.MouseEvent) => {
const viewport = viewportRef?.current
const scrollbar = scrollbarRef.current
if (!viewport || !scrollbar || e.target !== scrollbar) return
const rect = scrollbar.getBoundingClientRect()
const clickPos =
orientation === "vertical" ? e.clientY - rect.top : e.clientX - rect.left
const scrollbarSize = orientation === "vertical" ? rect.height : rect.width
const clickRatio = clickPos / scrollbarSize
const targetScroll = clickRatio * contentSize - viewportSize / 2
if (orientation === "vertical") {
viewport.scrollTop = Math.max(0, Math.min(targetScroll, contentSize - viewportSize))
} else {
viewport.scrollLeft = Math.max(0, Math.min(targetScroll, contentSize - viewportSize))
}
}
return (
<div
ref={scrollbarRef}
data-slot="scroll-area-scrollbar"
data-orientation={orientation}
className={cn(
"absolute flex touch-none p-px transition-opacity select-none",
orientation === "vertical" && "right-0 top-0 h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" && "bottom-0 left-0 h-2.5 w-full flex-col border-t border-t-transparent",
!isHovered && !isDragging && "opacity-0",
(isHovered || isDragging) && "opacity-100",
className
)}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onClick={handleTrackClick}
{...props}
>
<div
data-slot="scroll-area-thumb"
className={cn(
"bg-border relative rounded-full transition-colors",
orientation === "vertical" && "w-full",
orientation === "horizontal" && "h-full",
isDragging && "bg-foreground/50"
)}
style={{
[orientation === "vertical" ? "height" : "width"]: `${thumbSize}%`,
[orientation === "vertical" ? "top" : "left"]: `${thumbPosition}%`,
position: "absolute",
}}
onMouseDown={handleThumbMouseDown}
/>
</div>
)
}
export { ScrollArea, ScrollBar }

287
components/ui/select.tsx Normal file
View File

@@ -0,0 +1,287 @@
import React, {
createContext,
useContext,
useState,
useRef,
useEffect,
useCallback,
} from 'react';
import { cn } from '@/lib/utils';
interface SelectContextType {
open: boolean;
setOpen: (open: boolean) => void;
value: string;
setValue: (value: string) => void;
}
const SelectContext = createContext<SelectContextType | undefined>(undefined);
function useSelect() {
const context = useContext(SelectContext);
if (!context) {
throw new Error('Select components must be used within a Select');
}
return context;
}
interface SelectProps {
value?: string;
onValueChange?: (value: string) => void;
children: React.ReactNode;
}
function Select({
value: controlledValue,
onValueChange,
children,
}: SelectProps) {
const [internalValue, setInternalValue] = useState('');
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const isControlled = controlledValue !== undefined;
const value = isControlled ? controlledValue : internalValue;
const handleValueChange = useCallback(
(newValue: string) => {
if (!isControlled) {
setInternalValue(newValue);
}
onValueChange?.(newValue);
setOpen(false);
},
[isControlled, onValueChange]
);
// Handle clicking outside to close the menu
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
setOpen(false);
}
}
if (open) {
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}
}, [open]);
return (
<SelectContext.Provider
value={{ open, setOpen, value, setValue: handleValueChange }}
>
<div ref={containerRef} data-slot="select" className="relative">
{children}
</div>
</SelectContext.Provider>
);
}
interface SelectTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
children: React.ReactNode;
placeholder?: string;
}
function SelectTrigger({
className,
children,
placeholder = 'Select...',
...props
}: SelectTriggerProps) {
const { open, setOpen, value } = useSelect();
const triggerRef = useRef<HTMLButtonElement>(null);
return (
<button
ref={triggerRef}
data-slot="select-trigger"
onClick={() => setOpen(!open)}
className={cn(
'border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*="text-"])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 h-9 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4',
className
)}
{...props}
>
{children || <span className="text-muted-foreground">{placeholder}</span>}
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={cn(
'size-4 opacity-50 transition-transform',
open && 'rotate-180'
)}
>
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
);
}
interface SelectValueProps {
children?: React.ReactNode;
placeholder?: string;
}
function SelectValue({
children,
placeholder = 'Select...',
}: SelectValueProps) {
const { value } = useSelect();
return (
<span data-slot="select-value">{children || value || placeholder}</span>
);
}
interface SelectContentProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
function SelectContent({ className, children, ...props }: SelectContentProps) {
const { open } = useSelect();
const contentRef = useRef<HTMLDivElement>(null);
if (!open) return null;
return (
<div
ref={contentRef}
data-slot="select-content"
className={cn(
'bg-popover text-popover-foreground absolute z-50 min-w-[8rem] rounded-md border border-border shadow-md overflow-hidden top-full mt-2 left-0',
className
)}
{...props}
>
<div className="p-1 overflow-y-auto max-h-60">{children}</div>
</div>
);
}
interface SelectItemProps extends React.HTMLAttributes<HTMLDivElement> {
value: string;
children: React.ReactNode;
disabled?: boolean;
}
function SelectItem({
value,
children,
disabled = false,
className,
...props
}: SelectItemProps) {
const { value: selectedValue, setValue } = useSelect();
const isSelected = selectedValue === value;
return (
<div
data-slot="select-item"
onClick={() => !disabled && setValue(value)}
className={cn(
'focus:bg-accent focus:text-accent-foreground [&_svg:not([class*="text-"])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none transition-colors',
!disabled &&
'hover:bg-accent hover:text-accent-foreground cursor-pointer',
disabled && 'pointer-events-none opacity-50',
isSelected && 'bg-accent text-accent-foreground',
className
)}
{...props}
>
{isSelected && (
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
>
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
</span>
)}
{children}
</div>
);
}
interface SelectGroupProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
function SelectGroup({ className, children, ...props }: SelectGroupProps) {
return (
<div
data-slot="select-group"
className={cn('overflow-hidden', className)}
{...props}
>
{children}
</div>
);
}
interface SelectLabelProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
function SelectLabel({ className, children, ...props }: SelectLabelProps) {
return (
<div
data-slot="select-label"
className={cn(
'text-muted-foreground px-2 py-1.5 text-xs font-semibold',
className
)}
{...props}
>
{children}
</div>
);
}
interface SelectSeparatorProps extends React.HTMLAttributes<HTMLDivElement> {}
function SelectSeparator({ className, ...props }: SelectSeparatorProps) {
return (
<div
data-slot="select-separator"
className={cn(
'bg-border pointer-events-none -mx-1 my-1 h-px',
className
)}
{...props}
/>
);
}
export {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
SelectGroup,
SelectLabel,
SelectSeparator,
};

View File

@@ -0,0 +1,34 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
interface SeparatorProps extends React.HTMLAttributes<HTMLDivElement> {
orientation?: "horizontal" | "vertical"
decorative?: boolean
}
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: SeparatorProps) {
return (
<div
data-slot="separator"
role={decorative ? "none" : "separator"}
aria-orientation={decorative ? undefined : orientation}
data-orientation={orientation}
className={cn(
"bg-border shrink-0",
orientation === "horizontal" ? "h-px w-full" : "h-full w-px",
className
)}
{...props}
/>
)
}
export { Separator }

306
components/ui/sheet.tsx Normal file
View File

@@ -0,0 +1,306 @@
import React, { useState, useCallback, useContext, createContext } from 'react';
import { createPortal } from 'react-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
interface SheetContextType {
open: boolean;
setOpen: (open: boolean) => void;
side: 'top' | 'right' | 'bottom' | 'left';
}
const SheetContext = createContext<SheetContextType | undefined>(undefined);
function useSheet() {
const context = useContext(SheetContext);
if (!context) {
throw new Error('Sheet components must be used within a Sheet');
}
return context;
}
interface SheetProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
children: React.ReactNode;
side?: 'top' | 'right' | 'bottom' | 'left';
}
function Sheet({
open: controlledOpen,
onOpenChange,
children,
side = 'right',
}: SheetProps) {
const [internalOpen, setInternalOpen] = useState(false);
const isControlled = controlledOpen !== undefined;
const open = isControlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(newOpen: boolean) => {
if (!isControlled) {
setInternalOpen(newOpen);
}
onOpenChange?.(newOpen);
},
[isControlled, onOpenChange]
);
return (
<SheetContext.Provider value={{ open, setOpen, side }}>
{children}
</SheetContext.Provider>
);
}
function SheetTrigger(
props: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }
) {
const { setOpen } = useSheet();
const { children, asChild, ...rest } = props;
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement, {
...rest,
onClick: (e: React.MouseEvent) => {
setOpen(true);
children.props.onClick?.(e);
},
});
}
return (
<button
data-slot="sheet-trigger"
{...rest}
onClick={(e) => {
setOpen(true);
props.onClick?.(e);
}}
>
{children}
</button>
);
}
function SheetPortal({ children }: { children: React.ReactNode }) {
return createPortal(children, document.body);
}
function SheetOverlay({
className,
onClick,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
const { setOpen } = useSheet();
return (
<motion.div
data-slot="sheet-overlay"
className={cn('fixed inset-0 z-50 bg-black/50', className)}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3 }}
onClick={(e) => {
setOpen(false);
onClick?.(e);
}}
{...props}
/>
);
}
interface SheetContentProps extends React.HTMLAttributes<HTMLDivElement> {
showCloseButton?: boolean;
}
function SheetContent({
className,
children,
showCloseButton = true,
...props
}: SheetContentProps) {
const { setOpen, side } = useSheet();
const sideClasses = {
right: 'inset-y-0 right-0 h-full w-3/4 sm:max-w-sm border-l',
left: 'inset-y-0 left-0 h-full w-3/4 sm:max-w-sm border-r',
top: 'inset-x-0 top-0 h-auto border-b',
bottom: 'inset-x-0 bottom-0 h-auto border-t',
};
const slideVariants = {
right: {
initial: { x: 400, opacity: 0 },
animate: { x: 0, opacity: 1 },
exit: { x: 400, opacity: 0 },
},
left: {
initial: { x: -400, opacity: 0 },
animate: { x: 0, opacity: 1 },
exit: { x: -400, opacity: 0 },
},
top: {
initial: { y: -400, opacity: 0 },
animate: { y: 0, opacity: 1 },
exit: { y: -400, opacity: 0 },
},
bottom: {
initial: { y: 400, opacity: 0 },
animate: { y: 0, opacity: 1 },
exit: { y: 400, opacity: 0 },
},
};
return (
<SheetPortal>
<SheetOverlay />
<motion.div
data-slot="sheet-content"
className={cn(
'bg-background fixed z-50 flex flex-col gap-0 shadow-lg',
sideClasses[side]
)}
variants={slideVariants[side]}
initial="initial"
animate="animate"
exit="exit"
transition={{ type: 'spring', stiffness: 300, damping: 30 }}
{...props}
>
{children}
{showCloseButton && (
<button
data-slot="sheet-close"
onClick={() => setOpen(false)}
className="absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none"
aria-label="Close"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
>
<path d="M18 6l-12 12M6 6l12 12" />
</svg>
</button>
)}
</motion.div>
</SheetPortal>
);
}
function SheetClose(
props: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }
) {
const { setOpen } = useSheet();
const { children, asChild, ...rest } = props;
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement, {
...rest,
onClick: (e: React.MouseEvent) => {
setOpen(false);
children.props.onClick?.(e);
},
});
}
return (
<button
data-slot="sheet-close"
{...rest}
onClick={(e) => {
setOpen(false);
props.onClick?.(e);
}}
>
{children}
</button>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-header"
className={cn(
'flex flex-col gap-1.5 p-6 border-b border-border',
className
)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-footer"
className={cn(
'flex flex-col-reverse gap-2 p-6 border-t border-border sm:flex-row sm:justify-end',
className
)}
{...props}
/>
);
}
function SheetTitle({ className, ...props }: React.ComponentProps<'h2'>) {
return (
<h2
data-slot="sheet-title"
className={cn('text-lg leading-none font-semibold', className)}
{...props}
/>
);
}
function SheetDescription({ className, ...props }: React.ComponentProps<'p'>) {
return (
<p
data-slot="sheet-description"
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
);
}
interface SheetBodyProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
function SheetBody({ className, children, ...props }: SheetBodyProps) {
return (
<div
data-slot="sheet-body"
className={cn('flex-1 overflow-y-auto px-6 py-4', className)}
{...props}
>
{children}
</div>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
SheetBody,
SheetPortal,
SheetOverlay,
AnimatePresence,
};

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

23
components/ui/sonner.tsx Normal file
View File

@@ -0,0 +1,23 @@
import React from 'react';
import { toast } from 'sonner';
import Button from '@/components/ui/button';
export function SonnerDemo() {
return (
<Button
variant="outline"
onClick={() =>
toast('Event has been created', {
description: 'Sunday, December 03, 2023 at 9:00 AM',
action: {
label: 'Undo',
onClick: () => console.log('Undo'),
},
})
}
>
Show Toast
</Button>
);
}

38
components/ui/spinner.tsx Normal file
View File

@@ -0,0 +1,38 @@
import React from 'react';
import { cn } from '@/lib/utils';
interface SpinnerProps extends React.ComponentProps<'svg'> {
size?: 'sm' | 'md' | 'lg' | 'xl';
}
const sizeClasses = {
sm: 'size-3',
md: 'size-4',
lg: 'size-6',
xl: 'size-8',
};
function Spinner({ className, size = 'md', ...props }: SpinnerProps) {
return (
<svg
role="status"
aria-label="Loading"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={cn('animate-spin', sizeClasses[size], className)}
{...props}
>
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
);
}
export { Spinner };
export type { SpinnerProps };

74
components/ui/switch.tsx Normal file
View File

@@ -0,0 +1,74 @@
import React from 'react';
import { cn } from '@/lib/utils';
interface SwitchProps extends Omit<
React.InputHTMLAttributes<HTMLInputElement>,
'type'
> {
checked?: boolean;
onCheckedChange?: (checked: boolean) => void;
}
const Switch = React.forwardRef<HTMLInputElement, SwitchProps>(
({ className, checked, onCheckedChange, disabled, ...props }, ref) => {
const [isChecked, setIsChecked] = React.useState(checked ?? false);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newChecked = e.target.checked;
setIsChecked(newChecked);
onCheckedChange?.(newChecked);
props.onChange?.(e);
};
React.useEffect(() => {
if (checked !== undefined) {
setIsChecked(checked);
}
}, [checked]);
return (
<div className="relative inline-flex">
<input
ref={ref}
type="checkbox"
checked={isChecked}
onChange={handleChange}
disabled={disabled}
className="sr-only"
{...props}
/>
<div
data-slot="switch"
className={cn(
'inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px]',
isChecked
? 'bg-primary focus-visible:ring-ring/50 focus-visible:border-ring'
: 'bg-input dark:bg-input/80 focus-visible:ring-ring/50 focus-visible:border-ring',
disabled && 'cursor-not-allowed opacity-50',
className
)}
onClick={() => {
if (!disabled) {
setIsChecked(!isChecked);
onCheckedChange?.(!isChecked);
}
}}
>
<div
data-slot="switch-thumb"
className={cn(
'bg-background dark:bg-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform',
isChecked
? 'translate-x-[calc(100%-2px)] dark:bg-primary-foreground'
: 'translate-x-0'
)}
/>
</div>
</div>
);
}
);
Switch.displayName = 'Switch';
export { Switch };

113
components/ui/table.tsx Normal file
View File

@@ -0,0 +1,113 @@
import React from 'react';
import { cn } from '@/lib/utils';
function Table({ className, ...props }: React.ComponentProps<'table'>) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto rounded-md border border-border"
>
<table
data-slot="table"
className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
return (
<thead
data-slot="table-header"
className={cn('[&_tr]:border-b border-border', className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
return (
<tbody
data-slot="table-body"
className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
return (
<tfoot
data-slot="table-footer"
className={cn(
'bg-muted/50 border-t border-border font-medium [&>tr]:last:border-b-0',
className
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
return (
<tr
data-slot="table-row"
className={cn(
'hover:bg-muted/50 data-[state=selected]:bg-muted border-b border-border transition-colors',
className
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
return (
<th
data-slot="table-head"
className={cn(
'text-foreground bg-muted/30 h-10 px-4 py-2 text-left align-middle font-semibold whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
return (
<td
data-slot="table-cell"
className={cn(
'p-4 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<'caption'>) {
return (
<caption
data-slot="table-caption"
className={cn('text-muted-foreground mt-4 text-sm', className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};

143
components/ui/tabs.tsx Normal file
View File

@@ -0,0 +1,143 @@
import React, { createContext, useContext, useState } from 'react';
import { cn } from '@/lib/utils';
interface TabsContextType {
activeTab: string;
setActiveTab: (value: string) => void;
}
const TabsContext = createContext<TabsContextType | undefined>(undefined);
function useTabs() {
const context = useContext(TabsContext);
if (!context) {
throw new Error('Tabs components must be used within a Tabs component');
}
return context;
}
interface TabsProps extends React.HTMLAttributes<HTMLDivElement> {
defaultValue?: string;
value?: string;
onValueChange?: (value: string) => void;
}
function Tabs({
className,
defaultValue,
value: controlledValue,
onValueChange,
children,
...props
}: TabsProps) {
const [internalValue, setInternalValue] = useState(defaultValue || '');
const isControlled = controlledValue !== undefined;
const activeTab = isControlled ? controlledValue : internalValue;
const handleValueChange = (newValue: string) => {
if (!isControlled) {
setInternalValue(newValue);
}
onValueChange?.(newValue);
};
return (
<TabsContext.Provider
value={{ activeTab, setActiveTab: handleValueChange }}
>
<div
data-slot="tabs"
className={cn('flex flex-col gap-2', className)}
{...props}
>
{children}
</div>
</TabsContext.Provider>
);
}
interface TabsListProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
function TabsList({ className, children, ...props }: TabsListProps) {
return (
<div
data-slot="tabs-list"
className={cn(
'bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]',
className
)}
role="tablist"
{...props}
>
{children}
</div>
);
}
interface TabsTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
value: string;
children: React.ReactNode;
}
function TabsTrigger({
className,
value,
children,
...props
}: TabsTriggerProps) {
const { activeTab, setActiveTab } = useTabs();
const isActive = activeTab === value;
return (
<button
data-slot="tabs-trigger"
role="tab"
aria-selected={isActive}
aria-controls={`tabs-content-${value}`}
className={cn(
'text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4',
isActive &&
'bg-background dark:bg-input/30 dark:border-input shadow-sm',
className
)}
onClick={() => setActiveTab(value)}
{...props}
>
{children}
</button>
);
}
interface TabsContentProps extends React.HTMLAttributes<HTMLDivElement> {
value: string;
children: React.ReactNode;
}
function TabsContent({
className,
value,
children,
...props
}: TabsContentProps) {
const { activeTab } = useTabs();
if (activeTab !== value) {
return null;
}
return (
<div
data-slot="tabs-content"
role="tabpanel"
id={`tabs-content-${value}`}
className={cn('flex-1 outline-none', className)}
{...props}
>
{children}
</div>
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

280
components/ui/tooltip.tsx Normal file
View File

@@ -0,0 +1,280 @@
"use client"
import * as React from "react"
import { createPortal } from "react-dom"
import { cn } from "@/lib/utils"
interface TooltipContextValue {
open: boolean
setOpen: (open: boolean) => void
triggerRef: React.RefObject<HTMLElement | null>
delayDuration: number
}
const TooltipContext = React.createContext<TooltipContextValue | null>(null)
function useTooltip() {
const context = React.useContext(TooltipContext)
if (!context) {
throw new Error("useTooltip must be used within a Tooltip")
}
return context
}
interface TooltipProviderProps {
children: React.ReactNode
delayDuration?: number
}
const TooltipProviderContext = React.createContext<{ delayDuration: number }>({
delayDuration: 0,
})
function TooltipProvider({
children,
delayDuration = 0,
}: TooltipProviderProps) {
return (
<TooltipProviderContext.Provider value={{ delayDuration }}>
{children}
</TooltipProviderContext.Provider>
)
}
interface TooltipProps {
children: React.ReactNode
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
delayDuration?: number
}
function Tooltip({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
delayDuration: propDelayDuration,
}: TooltipProps) {
const providerContext = React.useContext(TooltipProviderContext)
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen)
const triggerRef = React.useRef<HTMLElement>(null)
const isControlled = controlledOpen !== undefined
const open = isControlled ? controlledOpen : uncontrolledOpen
const delayDuration = propDelayDuration ?? providerContext.delayDuration
const setOpen = React.useCallback(
(value: boolean) => {
if (!isControlled) {
setUncontrolledOpen(value)
}
onOpenChange?.(value)
},
[isControlled, onOpenChange]
)
return (
<TooltipContext.Provider value={{ open, setOpen, triggerRef, delayDuration }}>
{children}
</TooltipContext.Provider>
)
}
interface TooltipTriggerProps extends React.HTMLAttributes<HTMLSpanElement> {
asChild?: boolean
}
function TooltipTrigger({
children,
asChild,
...props
}: TooltipTriggerProps) {
const { setOpen, triggerRef, delayDuration } = useTooltip()
const timeoutRef = React.useRef<NodeJS.Timeout | null>(null)
const handleMouseEnter = () => {
if (delayDuration > 0) {
timeoutRef.current = setTimeout(() => setOpen(true), delayDuration)
} else {
setOpen(true)
}
}
const handleMouseLeave = () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
timeoutRef.current = null
}
setOpen(false)
}
const handleFocus = () => {
setOpen(true)
}
const handleBlur = () => {
setOpen(false)
}
React.useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
}
}
}, [])
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children as React.ReactElement<any>, {
ref: triggerRef,
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave,
onFocus: handleFocus,
onBlur: handleBlur,
"data-slot": "tooltip-trigger",
})
}
return (
<span
ref={triggerRef as React.RefObject<HTMLSpanElement>}
data-slot="tooltip-trigger"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onFocus={handleFocus}
onBlur={handleBlur}
{...props}
>
{children}
</span>
)
}
interface TooltipContentProps extends React.HTMLAttributes<HTMLDivElement> {
side?: "top" | "right" | "bottom" | "left"
sideOffset?: number
align?: "start" | "center" | "end"
}
function TooltipContent({
className,
side = "top",
sideOffset = 4,
align = "center",
children,
...props
}: TooltipContentProps) {
const { open, triggerRef } = useTooltip()
const [position, setPosition] = React.useState({ top: 0, left: 0 })
const [mounted, setMounted] = React.useState(false)
const contentRef = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
setMounted(true)
}, [])
React.useLayoutEffect(() => {
if (!open || !triggerRef.current || !contentRef.current) return
const trigger = triggerRef.current.getBoundingClientRect()
const content = contentRef.current.getBoundingClientRect()
let top = 0
let left = 0
// Calculate position based on side
switch (side) {
case "top":
top = trigger.top - content.height - sideOffset
break
case "bottom":
top = trigger.bottom + sideOffset
break
case "left":
left = trigger.left - content.width - sideOffset
top = trigger.top + (trigger.height - content.height) / 2
break
case "right":
left = trigger.right + sideOffset
top = trigger.top + (trigger.height - content.height) / 2
break
}
// Calculate alignment for top/bottom
if (side === "top" || side === "bottom") {
switch (align) {
case "start":
left = trigger.left
break
case "center":
left = trigger.left + (trigger.width - content.width) / 2
break
case "end":
left = trigger.right - content.width
break
}
}
// Calculate alignment for left/right
if (side === "left" || side === "right") {
switch (align) {
case "start":
top = trigger.top
break
case "center":
top = trigger.top + (trigger.height - content.height) / 2
break
case "end":
top = trigger.bottom - content.height
break
}
}
setPosition({ top, left })
}, [open, side, align, sideOffset, triggerRef])
if (!open || !mounted) return null
const slideClasses = {
top: "animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2",
bottom: "animate-in fade-in-0 zoom-in-95 slide-in-from-top-2",
left: "animate-in fade-in-0 zoom-in-95 slide-in-from-right-2",
right: "animate-in fade-in-0 zoom-in-95 slide-in-from-left-2",
}
return createPortal(
<div
ref={contentRef}
data-slot="tooltip-content"
data-state={open ? "open" : "closed"}
data-side={side}
role="tooltip"
className={cn(
"fixed z-50 w-max rounded-md bg-foreground px-3 py-1.5 text-xs text-background text-balance",
slideClasses[side],
className
)}
style={{
top: position.top,
left: position.left,
}}
{...props}
>
{children}
<div
className={cn(
"absolute size-2.5 rotate-45 rounded-[2px] bg-foreground",
side === "top" && "top-full left-1/2 -translate-x-1/2 -translate-y-1/2",
side === "bottom" && "bottom-full left-1/2 -translate-x-1/2 translate-y-1/2",
side === "left" && "left-full top-1/2 -translate-x-1/2 -translate-y-1/2",
side === "right" && "right-full top-1/2 translate-x-1/2 -translate-y-1/2"
)}
/>
</div>,
document.body
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }