Initial commit: Shopify storefront Next.js template

Next.js 16 + React 19 storefront template with Shopify Storefront API
integration, Tailwind v4, and shadcn/ui components.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111qSr3KopyGRsJ6LznR1xZ
This commit is contained in:
Rami Bitar
2026-07-31 22:12:19 -04:00
co-authored by Claude Opus 5
commit e3d5e75299
69 changed files with 7960 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
.DS_Store
node_modules/*
.next
next-env.d.ts
.yarn/install-state.gz
+1
View File
@@ -0,0 +1 @@
{}
+26
View File
@@ -0,0 +1,26 @@
import Header from '@/components/shopify/header';
import Footer from '@/components/shopify/footer';
import CollectionDetail from '@/components/shopify/collection-detail';
export default function Page() {
return (
<>
<Header
storeName="Stride"
logoUrl=""
links={[
{ label: 'Products', url: '/' },
{ label: 'Collections', url: '/collections' },
]}
/>
<CollectionDetail />
<Footer
storeName="Stride"
logoUrl=""
tagline="Your premium shopping destination"
copyright="© 2026 Stride. All rights reserved."
links={[]}
/>
</>
);
}
+26
View File
@@ -0,0 +1,26 @@
import Header from '@/components/shopify/header';
import Footer from '@/components/shopify/footer';
import Collections from '@/components/shopify/collections';
export default function Page() {
return (
<>
<Header
storeName="Stride"
logoUrl=""
links={[
{ label: 'Products', url: '/' },
{ label: 'Collections', url: '/collections' },
]}
/>
<Collections title="Our Collections" />
<Footer
storeName="Stride"
logoUrl=""
tagline="Your premium shopping destination"
copyright="© 2026 Stride. All rights reserved."
links={[]}
/>
</>
);
}
+96
View File
@@ -0,0 +1,96 @@
import { cn } from "@/lib/utils";
import type { HTMLAttributes } from "react";
interface LoaderIconProps {
size?: number;
}
const LoaderIcon = ({ size = 16 }: LoaderIconProps) => (
<svg
height={size}
strokeLinejoin="round"
style={{ color: "currentcolor" }}
viewBox="0 0 16 16"
width={size}
>
<title>Loader</title>
<g clipPath="url(#clip0_2393_1490)">
<path d="M8 0V4" stroke="currentColor" strokeWidth="1.5" />
<path
d="M8 16V12"
opacity="0.5"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M3.29773 1.52783L5.64887 4.7639"
opacity="0.9"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M12.7023 1.52783L10.3511 4.7639"
opacity="0.1"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M12.7023 14.472L10.3511 11.236"
opacity="0.4"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M3.29773 14.472L5.64887 11.236"
opacity="0.6"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M15.6085 5.52783L11.8043 6.7639"
opacity="0.2"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M0.391602 10.472L4.19583 9.23598"
opacity="0.7"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M15.6085 10.4722L11.8043 9.2361"
opacity="0.3"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M0.391602 5.52783L4.19583 6.7639"
opacity="0.8"
stroke="currentColor"
strokeWidth="1.5"
/>
</g>
<defs>
<clipPath id="clip0_2393_1490">
<rect fill="white" height="16" width="16" />
</clipPath>
</defs>
</svg>
);
export type LoaderProps = HTMLAttributes<HTMLDivElement> & {
size?: number;
};
export const Loader = ({ className, size = 16, ...props }: LoaderProps) => (
<div
className={cn(
"inline-flex animate-spin items-center justify-center",
className
)}
{...props}
>
<LoaderIcon size={size} />
</div>
);
+25
View File
@@ -0,0 +1,25 @@
"use client";
import React from 'react';
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="flex items-center gap-6">
<div className="text-lg font-medium text-black font-sans whitespace-nowrap">
Something went wrong
</div>
<div className="border-l border-gray-300 h-6"></div>
<div className="text-sm text-gray-700 font-sans max-w-lg">
{error.message}
</div>
</div>
</div>
);
}
+112
View File
@@ -0,0 +1,112 @@
@import 'tailwindcss';
@theme {
/* Refined neutral modern palette */
--color-background: hsl(0 0% 100%);
--color-foreground: hsl(240 10% 3.9%);
/* Card */
--color-card: hsl(0 0% 100%);
--color-card-foreground: hsl(240 10% 3.9%);
/* Popover */
--color-popover: hsl(0 0% 100%);
--color-popover-foreground: hsl(240 10% 3.9%);
/* Primary - Deep neutral slate for professional look */
--color-primary: hsl(240 5.9% 10%);
--color-primary-foreground: hsl(0 0% 98%);
/* Secondary */
--color-secondary: hsl(240 4.8% 95.9%);
--color-secondary-foreground: hsl(240 5.9% 10%);
/* Muted */
--color-muted: hsl(240 4.8% 95.9%);
--color-muted-foreground: hsl(240 3.8% 46.1%);
/* Accent - Subtle warm gray */
--color-accent: hsl(30 6.7% 95%);
--color-accent-foreground: hsl(240 5.9% 10%);
/* Destructive */
--color-destructive: hsl(0 84.2% 60.2%);
--color-destructive-foreground: hsl(0 0% 98%);
/* Border */
--color-border: hsl(240 5.9% 90%);
--color-input: hsl(240 5.9% 90%);
--color-ring: hsl(240 5.9% 10%);
/* Radius - Modern larger corners */
--radius-sm: 0.5rem;
--radius-md: 0.75rem;
--radius-lg: 1rem;
--radius-xl: 1.25rem;
/* Enhanced typography scale */
--font-heading: 'Space Grotesk', system-ui, sans-serif;
--font-body: 'Inter', system-ui, sans-serif;
--font-poppins: 'Poppins', system-ui, sans-serif;
}
/* Base styles for light, modern Shopify storefront */
body {
font-feature-settings:
'kern' 1,
'tnum' 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Modern card design for products and collections */
.card-modern {
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
border: 1px solid var(--color-border);
}
.card-modern:hover {
transform: translateY(-8px);
box-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.1);
border-color: hsl(240 5.9% 85%);
}
/* Bold heading styles */
h1,
h2,
.font-heading {
font-weight: 700;
letter-spacing: -0.025em;
}
/* Enhanced button styles */
button,
.btn-modern {
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.btn-modern:hover {
transform: translateY(-1px);
box-shadow:
0 10px 15px -3px rgb(0 0 0 / 0.1),
0 4px 6px -4px rgb(0 0 0 / 0.1);
}
/* Hero section styles */
.hero-bg {
background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f5 100%);
}
/* Product gallery improvements */
.product-gallery-main {
transition: box-shadow 0.3s ease;
}
.product-gallery-main:hover {
box-shadow: 0 0 0 1px hsl(240 5.9% 80%) inset;
}
/* Clean price display */
.price-display {
font-feature-settings: 'tnum';
}
+40
View File
@@ -0,0 +1,40 @@
'use client';
import React from 'react';
import './globals.css';
import { Space_Grotesk, Inter, Poppins } from 'next/font/google';
const poppins = Poppins({
subsets: ['latin'],
weight: ['400', '500', '600', '700'],
variable: '--font-poppins',
});
const spaceGrotesk = Space_Grotesk({
subsets: ['latin'],
weight: ['400', '500', '600', '700'],
variable: '--font-heading',
});
const inter = Inter({
subsets: ['latin'],
weight: ['400', '500', '600'],
variable: '--font-body',
});
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html
lang="en"
className={`${poppins.variable} ${spaceGrotesk.variable} ${inter.variable}`}
>
<body className="font-body antialiased bg-background text-foreground m-0 p-0">
{children}
</body>
</html>
);
}
+20
View File
@@ -0,0 +1,20 @@
"use client";
import React from 'react';
import Link from 'next/link';
export default function NotFound() {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="flex items-center gap-6">
<div className="text-lg font-medium text-black font-sans whitespace-nowrap">
404
</div>
<div className="border-l border-gray-300 h-6"></div>
<div className="text-sm text-gray-700 font-sans max-w-lg">
This page could not be found.
</div>
</div>
</div>
);
}
+26
View File
@@ -0,0 +1,26 @@
import Header from '@/components/shopify/header';
import Footer from '@/components/shopify/footer';
import Products from '@/components/shopify/products';
export default function Page() {
return (
<>
<Header
storeName="Stride"
logoUrl=""
links={[
{ label: 'Products', url: '/' },
{ label: 'Collections', url: '/collections' },
]}
/>
<Products title="Shop All" />
<Footer
storeName="Stride"
logoUrl=""
tagline="Your premium shopping destination"
copyright="© 2026 Stride. All rights reserved."
links={[]}
/>
</>
);
}
+35
View File
@@ -0,0 +1,35 @@
import Header from '@/components/shopify/header';
import Footer from '@/components/shopify/footer';
import ProductDetail from '@/components/shopify/product-detail';
import ProductRecommendations from '@/components/shopify/product-recommendations';
export default function Page() {
return (
<>
<Header
storeName="Stride"
logoUrl=""
links={[
{ label: 'Products', url: '/' },
{ label: 'Collections', url: '/collections' },
]}
/>
<ProductDetail
addToCartLabel="Add to Cart"
features={[
{ icon: 'RiTruckLine', label: 'Free shipping on orders over $100' },
{ icon: 'RiArrowGoBackLine', label: '30-day return policy' },
{ icon: 'RiSecurePaymentLine', label: 'Secure payment' },
]}
/>
<ProductRecommendations title="You Might Also Like" />
<Footer
storeName="Stride"
logoUrl=""
tagline="Your premium shopping destination"
copyright="© 2026 Stride. All rights reserved."
links={[]}
/>
</>
);
}
+26
View File
@@ -0,0 +1,26 @@
import Header from '@/components/shopify/header';
import Footer from '@/components/shopify/footer';
import Collections from '@/components/shopify/collections';
export default function Page() {
return (
<>
<Header
storeName="Stride"
logoUrl=""
links={[
{ label: 'Products', url: '/' },
{ label: 'Collections', url: '/shop/collections' },
]}
/>
<Collections title="Our Collections" />
<Footer
storeName="Stride"
logoUrl=""
tagline="Your premium shopping destination"
copyright="© 2026 Stride. All rights reserved."
links={[]}
/>
</>
);
}
+13
View File
@@ -0,0 +1,13 @@
import React from 'react';
const About: React.FC = () => {
return (
<div className="text-center">
<h1 className="text-5xl font-bold text-black mb-8" style={{fontFamily: 'Space Grotesk, sans-serif'}}>
About Page
</h1>
</div>
);
};
export default About;
+40
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';
+63
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>
);
}
+250
View File
@@ -0,0 +1,250 @@
'use client';
import React from 'react';
import { useCartStore, redirectToCheckout } from '@/hooks/use-shopify-cart';
import { Button } from '@/components/ui/button';
import { Loader } from '@/app/components/ui/loader';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetBody,
AnimatePresence,
} from '@/components/ui/sheet';
import {
RiCloseLine,
RiImageLine,
RiSubtractLine,
RiAddLine,
} from '@remixicon/react';
import {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
} from '@/components/ui/empty';
const CartDrawer: React.FC = () => {
const isOpen = useCartStore((s) => s.isOpen);
const closeCart = useCartStore((s) => s.closeCart);
const loading = useCartStore((s) => s.loading);
const cart = useCartStore((s) => s.cart);
const removeItem = useCartStore((s) => s.removeItem);
const updateItemQuantity = useCartStore((s) => s.updateItemQuantity);
const items = cart?.lines?.edges?.map((edge) => edge.node) ?? [];
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
const totalAmount = parseFloat(cart?.cost?.totalAmount?.amount ?? '0');
const checkoutUrl = cart?.checkoutUrl ?? null;
const handleCheckout = () => {
if (checkoutUrl) {
redirectToCheckout(checkoutUrl);
}
};
const getItemImage = (item: (typeof items)[0]) => {
return item.merchandise.image?.url;
};
const getSelectedOptions = (item: (typeof items)[0]) => {
return item.merchandise.selectedOptions ?? [];
};
return (
<Sheet
open={isOpen}
onOpenChange={(open) => !open && closeCart()}
side="right"
>
<AnimatePresence>
{isOpen && (
<SheetContent className="w-full max-w-md" showCloseButton={false}>
{/* Header */}
<SheetHeader className="h-14 min-h-0 px-4 py-3 flex items-center">
<div className="flex items-center justify-between w-full">
<SheetTitle className="text-base">
Shopping Cart ({itemCount})
</SheetTitle>
<Button onClick={closeCart} variant="ghost" size="icon-sm">
<RiCloseLine size={20} />
</Button>
</div>
</SheetHeader>
{/* Cart Items */}
<SheetBody>
{loading && items.length === 0 ? (
<div className="flex items-center justify-center py-12">
<Loader size={32} />
</div>
) : items.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyTitle>Your cart is empty</EmptyTitle>
<EmptyDescription>
Add some products to get started!
</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button onClick={closeCart} className="w-full">
Continue Shopping
</Button>
</EmptyContent>
</Empty>
) : (
<div className="space-y-6">
{items.map((item) => {
const image = getItemImage(item);
const selectedOptions = getSelectedOptions(item);
return (
<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">
{image ? (
<img
src={image}
alt={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 size={24} />
</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 */}
{selectedOptions.length > 0 && (
<div className="text-sm text-gray-500 mb-2">
{selectedOptions.map((option, index) => (
<span key={option.name}>
{option.value}
{index < 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)
}
variant="ghost"
size="icon-sm"
disabled={item.quantity <= 1 || loading}
className="h-7 w-7"
>
<RiSubtractLine size={14} />
</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)
}
variant="ghost"
size="icon-sm"
disabled={loading}
className="h-7 w-7"
>
<RiAddLine size={14} />
</Button>
</div>
</div>
</div>
{/* Price */}
<div className="flex-shrink-0">
<span className="text-sm 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)}
variant="ghost"
size="icon-sm"
disabled={loading}
className="text-gray-400 hover:text-red-500"
>
<RiCloseLine size={18} />
</Button>
</div>
</div>
);
})}
</div>
)}
</SheetBody>
{/* Footer - Checkout Section */}
{items.length > 0 && (
<div className="border-t border-border p-6">
{/* Subtotal */}
<div className="flex items-center justify-between mb-4">
<span className="text-base font-semibold">Subtotal</span>
<span className="text-lg font-bold">
${totalAmount.toFixed(2)}
</span>
</div>
<div className="text-sm text-gray-500 mb-4">
Shipping and taxes calculated at checkout
</div>
{/* Action Buttons */}
<div className="space-y-3">
<Button
onClick={handleCheckout}
disabled={loading || !checkoutUrl}
className="w-full"
size="lg"
>
{loading ? (
<span className="flex items-center justify-center space-x-2">
<Loader size={16} />
<span>Processing...</span>
</span>
) : (
'Checkout'
)}
</Button>
<Button onClick={closeCart} variant="link" className="w-full">
Continue Shopping
</Button>
</div>
</div>
)}
</SheetContent>
)}
</AnimatePresence>
</Sheet>
);
};
export default CartDrawer;
+71
View File
@@ -0,0 +1,71 @@
import React from 'react';
import Link from 'next/link';
import { Card, CardContent } from '@/components/ui/card';
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="group block h-full"
>
<div className="card-modern bg-card rounded-3xl overflow-hidden h-full flex flex-col shadow-sm">
{/* Collection Image */}
<div className="aspect-[16/10] relative overflow-hidden bg-zinc-100">
{collection.image ? (
<img
src={collection.image.url}
alt={collection.image.altText || collection.title}
className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
/>
) : (
<div className="absolute inset-0 flex flex-col items-center justify-center text-zinc-300">
<i className="ri-folder-line text-8xl mb-4"></i>
<span className="text-xs tracking-widest font-mono">
COLLECTION
</span>
</div>
)}
<div className="absolute inset-0 bg-gradient-to-b from-black/10 via-transparent to-black/30"></div>
</div>
{/* Collection Info */}
<div className="p-8 flex flex-col flex-1">
<h3 className="font-heading text-3xl font-semibold tracking-tighter text-foreground mb-4 group-hover:text-primary transition-colors">
{collection.title}
</h3>
{collection.description && (
<p className="text-muted-foreground text-[15px] leading-relaxed line-clamp-3 flex-1">
{collection.description}
</p>
)}
<div className="mt-8 flex items-center text-sm font-semibold text-primary group-hover:gap-x-2 transition-all">
EXPLORE COLLECTION
<i className="ri-arrow-right-line ml-2 text-base transition-transform group-hover:translate-x-0.5"></i>
</div>
</div>
</div>
</Link>
);
};
export default CollectionCard;
+110
View File
@@ -0,0 +1,110 @@
'use client';
import React from 'react';
import { useParams } from 'next/navigation';
import { useCollectionProducts } from '@/hooks/use-shopify-collections';
import ProductCard from './product-card';
const CollectionDetail: React.FC = () => {
const params = useParams();
const handle = params?.handle as string;
console.log('[CollectionDetail] params:', params, 'handle:', handle);
const { collection, loading, error, refetch } = useCollectionProducts(handle);
// Format title from handle
const formattedTitle = handle
? handle.replace(/-/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())
: 'Collection';
if (loading) {
return (
<div className="py-16">
<div className="container mx-auto px-4">
<h2 className="text-5xl font-bold text-center mb-16 text-gray-900 font-heading">
{formattedTitle}
</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="container mx-auto px-4 text-center">
<h2 className="text-5xl font-bold mb-8 font-heading">
{formattedTitle}
</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 Collection
</h3>
<p className="text-red-600 mb-4">{error}</p>
<button
onClick={() => refetch()}
className="bg-red-600 text-white px-6 py-2 rounded-lg hover:bg-red-700 transition-colors"
>
Try Again
</button>
</div>
</div>
</div>
);
}
const products = collection?.products || [];
const title = collection?.title || formattedTitle;
return (
<div className="py-16">
<div className="container mx-auto px-4">
<h2 className="text-5xl font-bold text-center mb-16 text-gray-900 font-heading">
{title}
</h2>
{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&apos;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">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
)}
</div>
</div>
);
};
export default CollectionDetail;
+121
View File
@@ -0,0 +1,121 @@
'use client';
import React from 'react';
import { useCollections } from '@/hooks/use-shopify-collections';
import CollectionCard from './collection-card';
import { Button } from '@/components/ui/button';
interface CollectionsProps {
title?: string;
}
const Collections: React.FC<CollectionsProps> = ({
title = 'Our Collections',
}) => {
const { collections, loading, error, refetch } = useCollections(12);
if (loading) {
return (
<div className="py-20">
<div className="max-w-screen-2xl mx-auto px-8">
<div className="flex justify-center mb-6">
<div className="inline px-6 py-2 bg-zinc-100 rounded-3xl text-xs font-mono tracking-widest text-muted-foreground">
EXPLORE
</div>
</div>
<h2 className="text-center text-6xl font-bold tracking-tighter font-heading mb-6 text-foreground">
{title}
</h2>
<p className="text-center text-muted-foreground max-w-md mx-auto mb-16">
Handpicked stories and themes
</p>
<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-3xl overflow-hidden animate-pulse border border-border h-[520px]"
>
<div className="h-80 bg-zinc-100"></div>
<div className="p-10 space-y-4">
<div className="h-8 bg-zinc-200 rounded-xl w-3/4"></div>
<div className="h-4 bg-zinc-200 rounded w-full"></div>
<div className="h-4 bg-zinc-200 rounded w-5/6"></div>
</div>
</div>
))}
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="py-20">
<div className="max-w-screen-2xl mx-auto px-8 text-center">
<h2 className="text-6xl font-bold tracking-tighter font-heading mb-8">
{title}
</h2>
<div className="mx-auto max-w-sm bg-white border border-border rounded-3xl p-10">
<i className="ri-alert-line text-5xl text-rose-500 mb-4"></i>
<h3 className="text-xl font-semibold mb-2">
Unable to load collections
</h3>
<p className="text-muted-foreground mb-6">{error}</p>
<Button onClick={refetch} variant="outline" className="btn-modern">
Retry
</Button>
</div>
</div>
</div>
);
}
if (collections.length === 0) {
return (
<div className="py-20 bg-zinc-50">
<div className="max-w-screen-2xl mx-auto px-8 text-center">
<h2 className="text-6xl font-bold tracking-tighter font-heading mb-8">
{title}
</h2>
<div className="mx-auto max-w-md p-12">
<i className="ri-folder-open-line text-6xl text-muted-foreground mb-6"></i>
<h3 className="text-2xl font-semibold mb-3">
No collections found
</h3>
<p className="text-muted-foreground">
Collections will appear here once added to your Shopify store.
</p>
</div>
</div>
</div>
);
}
return (
<div className="py-20">
<div className="max-w-screen-2xl mx-auto px-8">
<div className="flex justify-center mb-6">
<div className="inline px-6 py-2 bg-zinc-100 rounded-3xl text-xs font-mono tracking-widest text-muted-foreground">
THEMES &amp; STORIES
</div>
</div>
<h2 className="text-center text-6xl font-bold tracking-tighter font-heading mb-6 text-foreground">
{title}
</h2>
<p className="text-center text-muted-foreground max-w-md mx-auto mb-16 text-lg">
Discover our carefully crafted worlds
</p>
<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;
+121
View File
@@ -0,0 +1,121 @@
import React from 'react';
export interface FooterLink {
label: string;
url: string;
}
interface FooterProps {
storeName?: string;
logoUrl?: string;
tagline?: string;
copyright?: string;
links?: FooterLink[];
}
const Footer: React.FC<FooterProps> = ({
storeName = 'Stride',
logoUrl,
tagline = 'Performance in every stride.',
copyright = '© 2026 Stride. All rights reserved.',
links = [
{ label: 'About', url: '#' },
{ label: 'Athletes', url: '#' },
{ label: 'Technology', url: '#' },
{ label: 'Contact', url: '#' },
],
}) => {
return (
<footer className="bg-zinc-50 border-t border-border py-16 text-sm">
<div className="max-w-screen-2xl mx-auto px-8">
<div className="grid grid-cols-1 md:grid-cols-12 gap-y-12">
{/* Brand Column */}
<div className="md:col-span-5">
<div className="flex items-baseline mb-4">
{logoUrl ? (
<img
src={logoUrl}
alt={storeName}
className="h-8 w-auto object-contain"
/>
) : (
<span className="text-4xl font-semibold tracking-tighter font-poppins text-foreground">
{storeName}
</span>
)}
</div>
<p className="max-w-xs text-muted-foreground text-[15px] leading-relaxed">
{tagline}
</p>
<div className="mt-8 text-xs font-mono text-muted-foreground tracking-[1px]">
ENGINEERED FOR MOTION
</div>
</div>
{/* Links */}
<div className="md:col-span-3">
<div className="font-semibold text-foreground mb-5 text-xs tracking-widest">
SHOP
</div>
<div className="flex flex-col gap-y-3 text-muted-foreground">
{links.map((link, index) => (
<a
key={index}
href={link.url}
className="hover:text-foreground transition-colors w-fit"
>
{link.label}
</a>
))}
</div>
</div>
<div className="md:col-span-4">
<div className="font-semibold text-foreground mb-5 text-xs tracking-widest">
CONNECT
</div>
<div className="flex flex-col gap-y-3 text-muted-foreground">
<a
href="#"
className="hover:text-foreground transition-colors w-fit"
>
Instagram
</a>
<a
href="#"
className="hover:text-foreground transition-colors w-fit"
>
Pinterest
</a>
<a
href="#"
className="hover:text-foreground transition-colors w-fit"
>
Newsletter
</a>
</div>
<div className="mt-auto pt-12 text-[10px] text-muted-foreground font-mono leading-loose">
CRAFTED WITH PRECISION
<br />
IN A NEUTRAL PALETTE
</div>
</div>
</div>
{/* Bottom Bar */}
<div className="mt-16 pt-8 border-t border-border text-xs text-muted-foreground flex flex-col md:flex-row justify-between items-center gap-4 font-mono tracking-widest">
<div>{copyright}</div>
<div className="flex gap-x-6">
<span>Privacy</span>
<span>Terms</span>
</div>
</div>
</div>
</footer>
);
};
export default Footer;
+125
View File
@@ -0,0 +1,125 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { useCartStore } from '@/hooks/use-shopify-cart';
import CartDrawer from '@/components/shopify/cart-drawer';
import { RiShoppingCartLine, RiCloseLine, RiMenu3Line } from '@remixicon/react';
const CartIcon: React.FC = () => {
const toggleCart = useCartStore((s) => s.toggleCart);
const cart = useCartStore((s) => s.cart);
const itemCount =
cart?.lines?.edges?.reduce((sum, { node }) => sum + node.quantity, 0) ?? 0;
return (
<button
onClick={toggleCart}
className="relative p-2.5 text-foreground hover:text-primary transition-all duration-200 rounded-full hover:bg-secondary"
>
<RiShoppingCartLine size={20} />
{itemCount > 0 && (
<span className="absolute -top-0.5 -right-0.5 bg-primary text-primary-foreground text-[10px] font-mono rounded-full w-5 h-5 flex items-center justify-center font-semibold shadow">
{itemCount > 99 ? '99+' : itemCount}
</span>
)}
</button>
);
};
export interface NavLink {
label: string;
url: string;
}
interface HeaderProps {
storeName?: string;
logoUrl?: string;
links?: NavLink[];
}
const Header: React.FC<HeaderProps> = ({
storeName = 'STRIDE',
logoUrl,
links = [
{ label: 'Shop', url: '/' },
{ label: 'Collections', url: '/collections' },
],
}) => {
const [menuOpen, setMenuOpen] = useState(false);
return (
<nav className="bg-white/95 backdrop-blur-md border-b border-border sticky top-0 z-50">
<div className="max-w-screen-2xl mx-auto px-8">
<div className="flex justify-between items-center h-20">
{/* Logo */}
<Link href="/" className="flex items-center group">
{logoUrl ? (
<img
src={logoUrl}
alt={storeName}
className="h-9 w-auto object-contain"
/>
) : (
<span className="text-4xl font-semibold tracking-tighter font-poppins text-foreground group-hover:text-primary transition-colors">
{storeName}
</span>
)}
</Link>
{/* Desktop Navigation */}
<div className="hidden md:flex items-center gap-x-10 text-sm font-medium">
{links.map((link, index) => (
<Link
key={index}
href={link.url}
className="text-foreground hover:text-primary relative after:absolute after:bottom-[-2px] after:left-0 after:h-[2px] after:w-0 after:bg-primary after:transition-all hover:after:w-full"
>
{link.label}
</Link>
))}
</div>
{/* Actions */}
<div className="flex items-center gap-x-2">
<CartIcon />
{/* Mobile hamburger */}
<button
onClick={() => setMenuOpen(!menuOpen)}
className="md:hidden p-2.5 text-foreground hover:text-primary transition-all rounded-full hover:bg-secondary"
aria-label="Toggle menu"
>
{menuOpen ? <RiCloseLine size={28} /> : <RiMenu3Line size={28} />}
</button>
</div>
</div>
</div>
{/* Mobile Menu */}
{menuOpen && (
<div className="md:hidden border-t bg-white">
<div className="max-w-screen-2xl mx-auto px-8 py-8 flex flex-col gap-y-6 text-lg font-medium">
{links.map((link, index) => (
<Link
key={index}
href={link.url}
onClick={() => setMenuOpen(false)}
className="text-foreground hover:text-primary transition-colors py-1"
>
{link.label}
</Link>
))}
<div className="pt-4 border-t text-xs text-muted-foreground font-mono tracking-widest">
PROFESSIONAL CLEAN MODERN
</div>
</div>
</div>
)}
<CartDrawer />
</nav>
);
};
export default Header;
+179
View File
@@ -0,0 +1,179 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { useShopifyCart } from '@/hooks/use-shopify-cart';
import { truncate } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader } from '@/app/components/ui/loader';
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;
}
const ProductCard: React.FC<ProductCardProps> = ({ product, onAddToCart }) => {
const { addItem, openCart } = useShopifyCart();
const [isAdding, setIsAdding] = useState(false);
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 formatPrice = (amount: string) => {
return `$${parseFloat(amount).toFixed(2)}`;
};
const handleAddToCart = async (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (!firstVariant || !isAvailable || isAdding) return;
try {
setIsAdding(true);
await addItem(firstVariant.id, 1);
openCart();
if (onAddToCart) onAddToCart(product);
} catch (err) {
console.error('Failed to add item to cart:', err);
} finally {
setIsAdding(false);
}
};
return (
<div className="card-modern group bg-card rounded-2xl overflow-hidden h-full flex flex-col">
{/* Product Image */}
<div className="relative aspect-[4/3.1] bg-zinc-100 overflow-hidden">
<Link href={`/products/${product.handle}`} className="block h-full">
{firstImage ? (
<img
src={firstImage.url}
alt={firstImage.altText || product.title}
className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-[1.08]"
/>
) : (
<div className="absolute inset-0 flex items-center justify-center text-zinc-300">
<i className="ri-image-line text-8xl"></i>
</div>
)}
</Link>
{/* Badges */}
{hasDiscount && compareAtPrice && (
<Badge className="absolute top-4 left-4 bg-rose-600 hover:bg-rose-600 text-white text-xs font-medium px-3 py-1 shadow-sm">
SALE
</Badge>
)}
{!isAvailable && (
<div className="absolute top-4 right-4 bg-white/90 text-xs font-medium px-3 py-1 rounded-full border text-foreground/70">
SOLD OUT
</div>
)}
</div>
{/* Product Info */}
<div className="flex-1 p-6 flex flex-col">
<Link
href={`/products/${product.handle}`}
className="group-hover:text-primary transition-colors"
>
<h3 className="font-heading text-xl font-semibold tracking-tight text-foreground mb-2 line-clamp-2 min-h-[3.2em]">
{truncate(product.title, 65)}
</h3>
</Link>
<div className="mt-auto">
<div className="price-display flex items-baseline gap-x-3 mb-6">
<span className="text-2xl font-semibold text-foreground tracking-tighter">
{formatPrice(price.amount)}
</span>
{hasDiscount && compareAtPrice && (
<span className="text-base line-through text-muted-foreground">
{formatPrice(compareAtPrice.amount)}
</span>
)}
</div>
<div className="flex gap-3">
<Link href={`/products/${product.handle}`} className="flex-1">
<Button
variant="outline"
className="w-full btn-modern text-sm font-medium"
>
DETAILS
</Button>
</Link>
{isAvailable && (
<Button
onClick={handleAddToCart}
className="flex-1 btn-modern bg-primary hover:bg-primary/90 text-sm font-medium"
disabled={isAdding || !isAvailable}
>
{isAdding ? (
<>
<Loader size={16} className="mr-2" />
ADDING...
</>
) : (
'ADD TO BAG'
)}
</Button>
)}
</div>
</div>
</div>
</div>
);
};
export default ProductCard;
+3
View File
@@ -0,0 +1,3 @@
import ProductDetail from './product-detail/index';
export default ProductDetail;
+223
View File
@@ -0,0 +1,223 @@
'use client';
import React, { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { useProduct, type Product } from '@/hooks/use-shopify-products';
import { useShopifyCart } from '@/hooks/use-shopify-cart';
import ProductDetailGallery from './product-detail-gallery';
import ProductDetailInfo, { type ProductFeature } from './product-detail-info';
import { Button } from '@/components/ui/button';
import {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
} from '@/components/ui/empty';
import {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
} from '@/components/ui/breadcrumb';
interface ProductVariant {
id: string;
title: string;
price: {
amount: string;
currencyCode: string;
};
availableForSale: boolean;
selectedOptions: Array<{
name: string;
value: string;
}>;
image?: {
url: string;
altText?: string;
};
}
export type { Product };
interface ProductDetailProps {
handle?: string;
addToCartLabel?: string;
features?: ProductFeature[];
}
const ProductDetail: React.FC<ProductDetailProps> = ({
handle: handleProp,
addToCartLabel = 'Add to Cart',
features,
}) => {
const params = useParams();
const handle = handleProp || (params?.handle as string);
const { addItem, openCart } = useShopifyCart();
const { product, loading, error } = useProduct(handle);
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 [addingToCart, setAddingToCart] = useState(false);
// Initialize variant when product loads
useEffect(() => {
if (product) {
const firstVariant = product.variants.edges[0]?.node;
if (firstVariant) {
setSelectedVariant(firstVariant);
const initialOptions: Record<string, string> = {};
firstVariant.selectedOptions.forEach(
(option: { name: string; value: string }) => {
initialOptions[option.name] = option.value;
}
);
setSelectedOptions(initialOptions);
}
}
}, [product]);
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 variantImageUrl = matchingVariant.node.image.url;
const imageIndex = product.images.edges.findIndex(
(edge) => edge.node.url === variantImageUrl
);
if (imageIndex !== -1) {
setSelectedImageIndex(imageIndex);
}
}
}
};
const handleAddToCart = async () => {
if (!selectedVariant || !product) return;
try {
setAddingToCart(true);
await addItem(selectedVariant.id, quantity);
openCart();
} catch (err) {
console.error('Failed to add item to cart:', err);
} finally {
setAddingToCart(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">
<Empty className="min-h-[400px]">
<EmptyHeader>
<EmptyTitle>Product Not Found</EmptyTitle>
<EmptyDescription>
{error || 'The requested product could not be found.'}
</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button onClick={() => window.history.back()} variant="outline">
Go Back
</Button>
</EmptyContent>
</Empty>
</div>
);
}
return (
<div className="bg-white">
<div className="container mx-auto px-4 py-8">
<Breadcrumb className="mb-6">
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink asChild>
<Link href="/">Home</Link>
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>{product.title}</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
<ProductDetailGallery
images={product.images.edges.map((edge) => edge.node)}
selectedImageIndex={selectedImageIndex}
onImageSelect={setSelectedImageIndex}
/>
<ProductDetailInfo
product={product}
selectedVariant={selectedVariant}
selectedOptions={selectedOptions}
quantity={quantity}
setQuantity={setQuantity}
handleAddToCart={handleAddToCart}
onOptionChange={handleOptionChange}
loading={addingToCart}
addToCartLabel={addToCartLabel}
features={features}
/>
</div>
</div>
</div>
);
};
export default ProductDetail;
@@ -0,0 +1,64 @@
import React from 'react';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductDetailGalleryProps {
images: ProductImage[];
selectedImageIndex?: number;
onImageSelect?: (index: number) => void;
}
const ProductDetailGallery: React.FC<ProductDetailGalleryProps> = ({
images,
selectedImageIndex = 0,
onImageSelect,
}) => {
const setSelectedImage = onImageSelect || (() => {});
return (
<div className="space-y-4">
{/* Main Image */}
<div className="product-gallery-main aspect-square bg-zinc-50 border border-border rounded-3xl overflow-hidden shadow-inner relative">
{images.length > 0 ? (
<img
src={images[selectedImageIndex].url}
alt={images[selectedImageIndex].altText || 'Product image'}
className="w-full h-full object-cover transition-all hover:scale-105 duration-700"
/>
) : (
<div className="absolute inset-0 flex items-center justify-center text-zinc-300">
<i className="ri-image-line text-[120px]"></i>
</div>
)}
</div>
{/* Image Thumbnails */}
{images.length > 1 && (
<div className="grid grid-cols-4 gap-3">
{images.map((image, index) => (
<button
key={index}
onClick={() => setSelectedImage(index)}
className={`aspect-square rounded-2xl overflow-hidden border transition-all duration-200 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-primary/30 ${
selectedImageIndex === index
? 'border-primary shadow-md scale-[1.03]'
: 'border-border hover:border-zinc-300'
}`}
>
<img
src={image.url}
alt={image.altText || 'Product thumbnail'}
className="w-full h-full object-cover"
/>
</button>
))}
</div>
)}
</div>
);
};
export default ProductDetailGallery;
@@ -0,0 +1,240 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader } from '@/app/components/ui/loader';
import RemixIcon from '@/components/ui/remix-icon';
interface ProductPrice {
amount: string;
currencyCode: string;
}
interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
selectedOptions: Array<{
name: string;
value: string;
}>;
}
interface ProductOption {
id: string;
name: string;
values: string[];
}
interface Product {
id: string;
title: string;
description?: string;
descriptionHtml?: string;
handle: string;
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
options: ProductOption[];
}
export interface ProductFeature {
icon: string;
label: string;
}
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;
loading?: boolean;
addToCartLabel?: string;
features?: ProductFeature[];
}
const ProductDetailInfo: React.FC<ProductDetailInfoProps> = ({
product,
selectedVariant,
selectedOptions,
quantity,
setQuantity,
handleAddToCart,
onOptionChange,
loading = false,
addToCartLabel = 'Add to Cart',
features = [
{ icon: 'RiTruckLine', label: 'Free shipping on orders over $100' },
{ icon: 'RiArrowGoBackLine', label: '30-day return policy' },
{ icon: 'RiSecurePaymentLine', label: 'Secure payment' },
],
}) => {
const formatPrice = (amount: string) => {
return `$${parseFloat(amount).toFixed(2)}`;
};
const price = selectedVariant?.price || product.priceRange.minVariantPrice;
const compareAtPrice = product.compareAtPriceRange?.minVariantPrice;
const hasDiscount =
compareAtPrice &&
parseFloat(compareAtPrice.amount) > parseFloat(price.amount);
return (
<div className="pt-2">
<div className="mb-2">
<div className="uppercase tracking-[3px] text-xs font-mono text-muted-foreground mb-1">
LUMINA COLLECTION
</div>
<h1 className="text-5xl md:text-6xl font-bold tracking-tighter font-heading text-foreground leading-none mb-6">
{product.title}
</h1>
</div>
{/* Price */}
<div className="flex items-center gap-x-4 mb-10">
<span className="text-4xl font-semibold tracking-tighter text-foreground price-display">
{formatPrice(price.amount)}
</span>
{hasDiscount && compareAtPrice && (
<>
<span className="text-2xl text-muted-foreground line-through tracking-tight">
{formatPrice(compareAtPrice.amount)}
</span>
<Badge
variant="destructive"
className="text-xs font-mono px-4 py-1"
>
SAVE{' '}
{Math.round(
((parseFloat(compareAtPrice.amount) -
parseFloat(price.amount)) /
parseFloat(compareAtPrice.amount)) *
100
)}
%
</Badge>
</>
)}
</div>
{/* Description */}
{product.description && (
<div className="prose text-muted-foreground mb-10 text-[15px] leading-relaxed max-w-prose">
{product.descriptionHtml ? (
<div
dangerouslySetInnerHTML={{ __html: product.descriptionHtml }}
/>
) : (
<p>{product.description}</p>
)}
</div>
)}
{/* Product Options */}
{product.options &&
product.options.map((option) => (
<div key={option.id} className="mb-8">
<div className="text-xs uppercase font-mono tracking-widest text-muted-foreground mb-3">
{option.name}
</div>
<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'
}
className={`rounded-2xl px-6 py-2.5 text-sm font-medium transition-all ${
selectedOptions[option.name] === value ? 'shadow-md' : ''
}`}
>
{value}
</Button>
))}
</div>
</div>
))}
{/* Quantity Selector */}
<div className="mb-8">
<div className="text-xs uppercase font-mono tracking-widest text-muted-foreground mb-3">
QUANTITY
</div>
<div className="inline-flex items-center border border-border rounded-2xl">
<Button
onClick={() => setQuantity(Math.max(1, quantity - 1))}
variant="ghost"
size="icon-sm"
className="rounded-l-2xl h-12 w-12"
disabled={quantity <= 1}
>
</Button>
<div className="px-8 font-mono text-lg font-semibold tabular-nums">
{quantity}
</div>
<Button
onClick={() => setQuantity(quantity + 1)}
variant="ghost"
size="icon-sm"
className="rounded-r-2xl h-12 w-12"
>
+
</Button>
</div>
</div>
{/* Add to Cart Button */}
<Button
onClick={handleAddToCart}
disabled={!selectedVariant?.availableForSale || loading}
size="lg"
className="w-full h-16 text-base font-medium tracking-wider rounded-3xl btn-modern"
>
{loading ? (
<>
<Loader size={18} className="mr-3" />
ADDING TO BAG...
</>
) : selectedVariant?.availableForSale ? (
String(addToCartLabel ?? 'Add to Cart').toUpperCase()
) : (
'OUT OF STOCK'
)}
</Button>
{/* Features */}
{features.length > 0 && (
<div className="mt-12 pt-10 border-t border-border">
<div className="space-y-6">
{features.map((feature, index) => (
<div key={index} className="flex gap-x-4 text-sm">
<div className="mt-0.5 text-primary">
<RemixIcon name={feature.icon} size={18} />
</div>
<div className="text-muted-foreground leading-snug">
{feature.label}
</div>
</div>
))}
</div>
</div>
)}
<div className="mt-12 text-[10px] font-mono text-center text-muted-foreground tracking-widest">
FREE SHIPPING EASY RETURNS SECURE CHECKOUT
</div>
</div>
);
};
export default ProductDetailInfo;
@@ -0,0 +1,76 @@
'use client';
import React from 'react';
import { useParams } from 'next/navigation';
import {
useProduct,
useProductRecommendations,
} from '@/hooks/use-shopify-products';
import ProductCard from './product-card';
interface ProductRecommendationsProps {
productId?: string;
title?: string;
}
const ProductRecommendations: React.FC<ProductRecommendationsProps> = ({
productId: productIdProp,
title = 'You Might Also Like These Products 2',
}) => {
const params = useParams();
const handle = params?.handle as string | undefined;
const { product } = useProduct(productIdProp ? null : (handle ?? null));
const resolvedProductId = productIdProp || product?.id || '';
const { recommendations, loading, error } = useProductRecommendations(
resolvedProductId || null
);
if (!loading && (!recommendations || recommendations.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 font-heading">
{title}
</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">
{recommendations.slice(0, 4).map((recommendedProduct) => (
<ProductCard
key={recommendedProduct.id}
product={recommendedProduct}
/>
))}
</div>
)}
</div>
</div>
);
};
export default ProductRecommendations;
+238
View File
@@ -0,0 +1,238 @@
'use client';
import React, { useState, useEffect } from 'react';
import ProductCard from './product-card';
import { getProducts } from '@/hooks/use-shopify-products';
import { Button } from '@/components/ui/button';
import { Loader } from '@/app/components/ui/loader';
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;
}
const Products: React.FC<ProductsProps> = ({
title = 'Our Products',
limit = 12,
showLoadMore = true,
}) => {
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) {
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) => {
console.log('Adding to cart:', product);
};
const handleLoadMore = () => {
if (!loadingMore && hasMoreProducts) {
fetchProducts(products, true);
}
};
if (loading) {
return (
<div className="py-20">
<div className="max-w-screen-2xl mx-auto px-8">
<div className="flex justify-center mb-6">
<div className="inline px-6 py-2 bg-white border rounded-3xl text-xs font-mono tracking-widest text-muted-foreground">
DISCOVER
</div>
</div>
<h2 className="text-center text-6xl font-bold tracking-tighter font-heading mb-5 text-foreground">
{title}
</h2>
<p className="text-center text-muted-foreground max-w-md mx-auto mb-16">
Loading our finest selection...
</p>
<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-3xl overflow-hidden animate-pulse border border-border h-[460px]"
>
<div className="h-[280px] bg-zinc-100"></div>
<div className="p-8 space-y-6">
<div className="h-6 bg-zinc-200 rounded-full w-4/5"></div>
<div className="h-4 bg-zinc-200 rounded w-1/3"></div>
<div className="pt-4 flex gap-3">
<div className="h-11 flex-1 bg-zinc-200 rounded-2xl"></div>
<div className="h-11 flex-1 bg-zinc-200 rounded-2xl"></div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
);
}
if (error || products.length === 0) {
return (
<div className="py-20 bg-zinc-50">
<div className="max-w-screen-2xl mx-auto px-8 text-center">
<h2 className="text-6xl font-bold tracking-tighter font-heading mb-8 text-foreground">
{title}
</h2>
<div className="mx-auto max-w-sm bg-white border border-border rounded-3xl p-12">
<i className="ri-inbox-line text-6xl text-muted-foreground mb-6 block"></i>
<h3 className="font-semibold text-2xl mb-3 tracking-tight">
{error ? 'Connection Error' : 'Coming Soon'}
</h3>
<p className="text-muted-foreground mb-8 text-base">
{error ||
'Our curated collection is being prepared. Please check back shortly.'}
</p>
{error && (
<Button onClick={() => fetchProducts()} className="btn-modern">
Try Again
</Button>
)}
</div>
</div>
</div>
);
}
return (
<div className="py-20 bg-white">
<div className="max-w-screen-2xl mx-auto px-8">
<div className="flex justify-center mb-6">
<div className="inline px-6 py-2 bg-zinc-100 rounded-3xl text-xs font-mono tracking-[1.5px] text-muted-foreground">
CURATED SELECTION
</div>
</div>
<h2 className="text-center text-6xl font-bold tracking-tighter font-heading mb-5 text-foreground">
{title}
</h2>
<p className="text-center text-muted-foreground max-w-md mx-auto mb-16 text-lg">
Beautifully designed objects for everyday life
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-x-8 gap-y-16 mb-20">
{products.map((product) => (
<ProductCard
key={product.id}
product={product}
onAddToCart={handleAddToCart}
/>
))}
</div>
{showLoadMore && hasMoreProducts && (
<div className="flex justify-center">
<Button
onClick={handleLoadMore}
disabled={loadingMore}
size="lg"
className="btn-modern rounded-2xl px-14 py-7 text-sm tracking-widest font-medium border border-border"
>
{loadingMore ? (
<>
<Loader size={18} className="mr-3" />
LOADING MORE
</>
) : (
'LOAD MORE PRODUCTS'
)}
</Button>
</div>
)}
</div>
</div>
);
};
export default Products;
+197
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
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
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 };
+54
View File
@@ -0,0 +1,54 @@
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)) {
const child = children as React.ReactElement<any>;
return React.cloneElement(child, {
className: cn(child.props.className, finalClassName),
...props,
} as any);
}
return (
<span data-slot="badge" className={finalClassName} {...props}>
{children}
</span>
);
}
export { Badge, badgeVariants };
export type { BadgeProps };
+149
View File
@@ -0,0 +1,149 @@
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)) {
const child = children as React.ReactElement<any>;
return React.cloneElement(child, {
className: cn(
'hover:text-foreground transition-colors',
child.props.className,
className
),
...props,
} as any);
}
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,
};
+97
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
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
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 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
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,
};
+268
View File
@@ -0,0 +1,268 @@
import React, { useState, useCallback, useContext, createContext } from 'react';
import { createPortal } from 'react-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { clsx } from 'clsx';
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)) {
const child = children as React.ReactElement<any>;
return React.cloneElement(child, {
...props,
onClick: (e: React.MouseEvent) => {
setOpen(true);
child.props.onClick?.(e);
},
} as any);
}
return (
<button
{...props}
onClick={(e) => {
setOpen(true);
props.onClick?.(e);
}}
>
{children}
</button>
);
}
function DialogPortal({ children }: { children: React.ReactNode }) {
return createPortal(children, document.body);
}
function DialogClose({
children,
asChild,
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }) {
const { setOpen } = useDialog();
if (asChild && React.isValidElement(children)) {
const child = children as React.ReactElement<any>;
return React.cloneElement(child, {
...props,
onClick: (e: React.MouseEvent) => {
setOpen(false);
child.props.onClick?.(e);
},
} as any);
}
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={clsx('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 as any)}
/>
);
}
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={clsx(
'bg-background fixed top-1/2 left-1/2 z-50 grid w-full max-w-screen-md max-w-[calc(100%-2rem)] -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 as any)}
>
{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={clsx(
'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={clsx(
'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={clsx('text-lg leading-none font-semibold', className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.HTMLAttributes<HTMLParagraphElement>) {
return (
<p
data-slot="dialog-description"
className={clsx('text-muted-foreground text-sm', className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
AnimatePresence,
};
+105
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,
}
+86
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
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
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,
};
+128
View File
@@ -0,0 +1,128 @@
import * as React from 'react';
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { 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(
'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',
isActive
? 'border border-border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground'
: 'hover:bg-accent hover:text-accent-foreground',
size === 'icon' && 'size-9',
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,
};
+44
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 };
+44
View File
@@ -0,0 +1,44 @@
'use client';
import React from 'react';
import * as RemixIcons from '@remixicon/react';
interface RemixIconProps {
name: string; // e.g. "RiTruckLine"
className?: string;
size?: number;
}
const RemixIcon: React.FC<RemixIconProps> = ({
name,
className,
size = 16,
}) => {
if (!name) return null;
// Normalise: accept "RiTruckLine", "ri-truck-line", or "riTruckLine"
const normalised = name
// ri-truck-line → RiTruckLine
.replace(/^ri-/, 'Ri')
.replace(/-([a-z])/g, (_, c) => c.toUpperCase())
// ensure first char is uppercase
.replace(/^./, (c) => c.toUpperCase());
const IconComponent = (
RemixIcons as Record<
string,
React.FC<{ className?: string; size?: number }>
>
)[normalised];
if (!IconComponent) {
console.warn(
`[RemixIcon] Icon "${name}" (resolved: "${normalised}") not found.`
);
return null;
}
return <IconComponent className={className} size={size} />;
};
export default RemixIcon;
+287
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,
};
+308
View File
@@ -0,0 +1,308 @@
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)) {
const child = children as React.ReactElement<any>;
return React.cloneElement(child, {
...rest,
onClick: (e: React.MouseEvent) => {
setOpen(true);
child.props.onClick?.(e);
},
} as any);
}
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 as any)}
/>
);
}
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 as any)}
>
{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)) {
const child = children as React.ReactElement<any>;
return React.cloneElement(child, {
...rest,
onClick: (e: React.MouseEvent) => {
setOpen(false);
child.props.onClick?.(e);
},
} as any);
}
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,
};
+13
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
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
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
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
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
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 };
+18
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 }
+137
View File
@@ -0,0 +1,137 @@
// Cart Fragment for consistent cart data
const CartFragment = `
fragment CartFragment on Cart {
id
checkoutUrl
totalQuantity
cost {
subtotalAmount {
amount
currencyCode
}
totalAmount {
amount
currencyCode
}
totalTaxAmount {
amount
currencyCode
}
}
lines(first: 100) {
edges {
node {
id
quantity
cost {
totalAmount {
amount
currencyCode
}
}
merchandise {
... on ProductVariant {
id
title
selectedOptions {
name
value
}
price {
amount
currencyCode
}
image {
id
url
altText
width
height
}
product {
id
title
handle
vendor
}
}
}
}
}
}
}
`;
// Create a new cart
export const CREATE_CART_MUTATION = `
${CartFragment}
mutation CreateCart($lines: [CartLineInput!]) {
cartCreate(input: { lines: $lines }) {
cart {
...CartFragment
}
userErrors {
field
message
}
}
}
`;
// Add lines to cart
export const ADD_CART_LINES_MUTATION = `
${CartFragment}
mutation AddCartLines($cartId: ID!, $lines: [CartLineInput!]!) {
cartLinesAdd(cartId: $cartId, lines: $lines) {
cart {
...CartFragment
}
userErrors {
field
message
}
}
}
`;
// Update cart lines
export const UPDATE_CART_LINES_MUTATION = `
${CartFragment}
mutation UpdateCartLines($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
cartLinesUpdate(cartId: $cartId, lines: $lines) {
cart {
...CartFragment
}
userErrors {
field
message
}
}
}
`;
// Remove lines from cart
export const REMOVE_CART_LINES_MUTATION = `
${CartFragment}
mutation RemoveCartLines($cartId: ID!, $lineIds: [ID!]!) {
cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
cart {
...CartFragment
}
userErrors {
field
message
}
}
}
`;
// Get cart by ID
export const GET_CART_QUERY = `
${CartFragment}
query GetCart($cartId: ID!) {
cart(id: $cartId) {
...CartFragment
}
}
`;
+61
View File
@@ -0,0 +1,61 @@
import { ProductFragment } from '@/graphql/products';
// Get all collections
export const GET_COLLECTIONS_QUERY = `
query GetCollections($first: Int!) {
collections(first: $first) {
edges {
node {
id
title
handle
description
descriptionHtml
image {
id
url
altText
width
height
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
`;
// Get products in a collection
export const GET_COLLECTION_PRODUCTS_QUERY = `
${ProductFragment}
query GetCollectionProducts($handle: String!, $first: Int!, $sortKey: ProductCollectionSortKeys, $reverse: Boolean) {
collection(handle: $handle) {
id
title
handle
description
descriptionHtml
image {
id
url
altText
width
height
}
products(first: $first, sortKey: $sortKey, reverse: $reverse) {
edges {
node {
...ProductFragment
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
`;
+117
View File
@@ -0,0 +1,117 @@
// Product Fragment for consistent product data
export const ProductFragment = `
fragment ProductFragment on Product {
id
title
handle
description
descriptionHtml
vendor
productType
tags
availableForSale
priceRange {
minVariantPrice {
amount
currencyCode
}
maxVariantPrice {
amount
currencyCode
}
}
compareAtPriceRange {
minVariantPrice {
amount
currencyCode
}
maxVariantPrice {
amount
currencyCode
}
}
images(first: 10) {
edges {
node {
id
url
altText
width
height
}
}
}
variants(first: 100) {
edges {
node {
id
title
availableForSale
quantityAvailable
selectedOptions {
name
value
}
price {
amount
currencyCode
}
compareAtPrice {
amount
currencyCode
}
image {
id
url
altText
width
height
}
}
}
}
options {
id
name
values
}
}
`;
// Get multiple products
export const GET_PRODUCTS_QUERY = `
${ProductFragment}
query GetProducts($first: Int!, $query: String, $sortKey: ProductSortKeys, $reverse: Boolean) {
products(first: $first, query: $query, sortKey: $sortKey, reverse: $reverse) {
edges {
node {
...ProductFragment
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
`;
// Get a single product by handle
export const GET_PRODUCT_QUERY = `
${ProductFragment}
query GetProduct($handle: String!) {
product(handle: $handle) {
...ProductFragment
}
}
`;
// Get product recommendations
export const QUERY_PRODUCT_RECOMMENDATIONS = `
${ProductFragment}
query GetProductRecommendations($productId: ID!) {
productRecommendations(productId: $productId) {
...ProductFragment
}
}
`;
+379
View File
@@ -0,0 +1,379 @@
'use client';
import { create } from 'zustand';
import { shopifyFetch } from '@/services/shopify/client';
import {
CREATE_CART_MUTATION,
ADD_CART_LINES_MUTATION,
UPDATE_CART_LINES_MUTATION,
REMOVE_CART_LINES_MUTATION,
GET_CART_QUERY,
} from '@/graphql/cart';
import { useEffect } from 'react';
// ─── Types ───────────────────────────────────────────────────────────
export interface CartLineInput {
merchandiseId: string;
quantity: number;
}
export interface CartLineUpdateInput {
id: string;
quantity: number;
}
interface CartLine {
id: string;
quantity: number;
cost: {
totalAmount: {
amount: string;
currencyCode: string;
};
};
merchandise: {
id: string;
title: string;
selectedOptions: Array<{
name: string;
value: string;
}>;
price: {
amount: string;
currencyCode: string;
};
image?: {
id: string;
url: string;
altText?: string;
width: number;
height: number;
};
product: {
id: string;
title: string;
handle: string;
vendor?: string;
};
};
}
export interface Cart {
id: string;
checkoutUrl: string;
totalQuantity: number;
cost: {
subtotalAmount: {
amount: string;
currencyCode: string;
};
totalAmount: {
amount: string;
currencyCode: string;
};
totalTaxAmount?: {
amount: string;
currencyCode: string;
};
};
lines: {
edges: Array<{
node: CartLine;
}>;
};
}
// ─── Shopify API functions ───────────────────────────────────────────
async function createCartApi(lines: CartLineInput[] = []): Promise<Cart> {
const response = await shopifyFetch({
query: CREATE_CART_MUTATION,
variables: { lines: lines.length > 0 ? lines : null },
});
if (response.data.cartCreate.userErrors.length > 0) {
throw new Error(response.data.cartCreate.userErrors[0].message);
}
return response.data.cartCreate.cart;
}
async function addCartLinesApi(
cartId: string,
lines: CartLineInput[]
): Promise<Cart> {
const response = await shopifyFetch({
query: ADD_CART_LINES_MUTATION,
variables: { cartId, lines },
});
if (response.data.cartLinesAdd.userErrors.length > 0) {
throw new Error(response.data.cartLinesAdd.userErrors[0].message);
}
return response.data.cartLinesAdd.cart;
}
async function updateCartLinesApi(
cartId: string,
lines: CartLineUpdateInput[]
): Promise<Cart> {
const response = await shopifyFetch({
query: UPDATE_CART_LINES_MUTATION,
variables: { cartId, lines },
});
if (response.data.cartLinesUpdate.userErrors.length > 0) {
throw new Error(response.data.cartLinesUpdate.userErrors[0].message);
}
return response.data.cartLinesUpdate.cart;
}
async function removeCartLinesApi(
cartId: string,
lineIds: string[]
): Promise<Cart> {
const response = await shopifyFetch({
query: REMOVE_CART_LINES_MUTATION,
variables: { cartId, lineIds },
});
if (response.data.cartLinesRemove.userErrors.length > 0) {
throw new Error(response.data.cartLinesRemove.userErrors[0].message);
}
return response.data.cartLinesRemove.cart;
}
async function getCartApi(cartId: string): Promise<Cart | null> {
const response = await shopifyFetch({
query: GET_CART_QUERY,
variables: { cartId },
});
return response.data.cart;
}
export function redirectToCheckout(checkoutUrl: string): void {
if (checkoutUrl) {
window.location.href = checkoutUrl;
}
}
// ─── Zustand Store ───────────────────────────────────────────────────
const CART_ID_KEY = 'cartId';
interface CartState {
// State
isOpen: boolean;
cartId: string | null;
cart: Cart | null;
loading: boolean;
error: string | null;
_initialized: boolean;
// Computed (derived in the hook)
// items, itemCount, totalAmount, checkoutUrl
// Actions
openCart: () => void;
closeCart: () => void;
toggleCart: () => void;
initCart: () => void;
addItem: (variantId: string, quantity?: number) => Promise<Cart>;
removeItem: (lineId: string) => Promise<Cart>;
updateItemQuantity: (lineId: string, quantity: number) => Promise<Cart>;
refreshCart: () => Promise<void>;
}
export const useCartStore = create<CartState>((set, get) => ({
// Initial state
isOpen: false,
cartId: null,
cart: null,
loading: true,
error: null,
_initialized: false,
// UI actions
openCart: () => set({ isOpen: true }),
closeCart: () => set({ isOpen: false }),
toggleCart: () => set((s) => ({ isOpen: !s.isOpen })),
// Initialize cart from localStorage
initCart: () => {
if (get()._initialized) return;
set({ _initialized: true });
if (typeof window === 'undefined') return;
const storedCartId = localStorage.getItem(CART_ID_KEY);
if (!storedCartId) {
set({ loading: false });
return;
}
set({ loading: true });
getCartApi(storedCartId)
.then((fetchedCart) => {
if (fetchedCart) {
set({ cart: fetchedCart, cartId: storedCartId, loading: false });
} else {
localStorage.removeItem(CART_ID_KEY);
set({ cartId: null, cart: null, loading: false });
}
})
.catch(() => {
localStorage.removeItem(CART_ID_KEY);
set({
cartId: null,
cart: null,
loading: false,
error: 'Failed to fetch cart',
});
});
},
// Add item to cart (creates cart if needed)
addItem: async (variantId: string, quantity: number = 1) => {
try {
set({ loading: true, error: null });
// Get or create cart
let currentCartId = get().cartId;
if (!currentCartId) {
const storedCartId = localStorage.getItem(CART_ID_KEY);
if (storedCartId) {
currentCartId = storedCartId;
set({ cartId: storedCartId });
} else {
const newCart = await createCartApi();
localStorage.setItem(CART_ID_KEY, newCart.id);
set({ cart: newCart, cartId: newCart.id });
currentCartId = newCart.id;
}
}
const updatedCart = await addCartLinesApi(currentCartId, [
{ merchandiseId: variantId, quantity },
]);
set({ cart: updatedCart, loading: false });
return updatedCart;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to add item to cart';
set({ error: errorMessage, loading: false });
throw err;
}
},
// Remove item from cart
removeItem: async (lineId: string) => {
const { cartId } = get();
if (!cartId) throw new Error('No cart exists');
try {
set({ loading: true, error: null });
const updatedCart = await removeCartLinesApi(cartId, [lineId]);
set({ cart: updatedCart, loading: false });
return updatedCart;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to remove item from cart';
set({ error: errorMessage, loading: false });
throw err;
}
},
// Update item quantity
updateItemQuantity: async (lineId: string, quantity: number) => {
const { cartId, removeItem } = get();
if (!cartId) throw new Error('No cart exists');
if (quantity <= 0) {
return removeItem(lineId);
}
try {
set({ loading: true, error: null });
const updatedCart = await updateCartLinesApi(cartId, [
{ id: lineId, quantity },
]);
set({ cart: updatedCart, loading: false });
return updatedCart;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to update item quantity';
set({ error: errorMessage, loading: false });
throw err;
}
},
// Refresh cart from Shopify
refreshCart: async () => {
const storedCartId = localStorage.getItem(CART_ID_KEY);
if (!storedCartId) {
set({ loading: false });
return;
}
try {
set({ loading: true, error: null });
const fetchedCart = await getCartApi(storedCartId);
if (fetchedCart) {
set({ cart: fetchedCart, cartId: storedCartId, loading: false });
} else {
localStorage.removeItem(CART_ID_KEY);
set({ cartId: null, cart: null, loading: false });
}
} catch (err) {
localStorage.removeItem(CART_ID_KEY);
set({
cartId: null,
cart: null,
loading: false,
error: 'Failed to fetch cart',
});
}
},
}));
// ─── Hook (backwards-compatible API) ─────────────────────────────────
export function useShopifyCart() {
const store = useCartStore();
// Initialize cart safely in an effect, not during render
useEffect(() => {
if (!store._initialized) {
store.initCart();
}
}, []);
const items = store.cart?.lines?.edges?.map((edge) => edge.node) ?? [];
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
const totalAmount = parseFloat(store.cart?.cost?.totalAmount?.amount ?? '0');
const checkoutUrl = store.cart?.checkoutUrl ?? null;
return {
isOpen: store.isOpen,
openCart: store.openCart,
closeCart: store.closeCart,
toggleCart: store.toggleCart,
cartId: store.cartId,
cart: store.cart,
items,
itemCount,
totalAmount,
checkoutUrl,
loading: store.loading,
error: store.error,
addItem: store.addItem,
removeItem: store.removeItem,
updateItemQuantity: store.updateItemQuantity,
refreshCart: store.refreshCart,
};
}
+127
View File
@@ -0,0 +1,127 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { shopifyFetch } from '@/services/shopify/client';
import {
GET_COLLECTIONS_QUERY,
GET_COLLECTION_PRODUCTS_QUERY,
} from '@/graphql/collections';
import type { Product } from '@/hooks/use-shopify-products';
interface CollectionImage {
url: string;
altText?: string;
}
export interface Collection {
id: string;
title: string;
handle: string;
description?: string;
descriptionHtml?: string;
image?: CollectionImage;
}
export interface CollectionWithProducts extends Collection {
products: Product[];
}
interface UseCollectionProductsOptions {
first?: number;
sortKey?: 'BEST_SELLING' | 'CREATED' | 'PRICE' | 'TITLE';
reverse?: boolean;
}
// Fetch all collections
export async function getCollections(first = 50): Promise<Collection[]> {
const response = await shopifyFetch({
query: GET_COLLECTIONS_QUERY,
variables: { first },
});
return response.data.collections.edges.map((edge: { node: Collection }) => edge.node);
}
// Fetch products in a collection by handle
export async function getCollectionProducts(
handle: string,
{ first = 50, sortKey = 'BEST_SELLING', reverse = false }: UseCollectionProductsOptions = {}
): Promise<CollectionWithProducts | null> {
const response = await shopifyFetch({
query: GET_COLLECTION_PRODUCTS_QUERY,
variables: { handle, first, sortKey, reverse },
});
const collection = response.data.collection;
if (!collection) return null;
return {
...collection,
products: collection.products.edges.map((edge: { node: Product }) => edge.node),
};
}
// Hook for fetching all collections
export function useCollections(first = 50) {
const [collections, setCollections] = useState<Collection[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchCollections = useCallback(async () => {
try {
setLoading(true);
setError(null);
const data = await getCollections(first);
setCollections(data);
} catch (err) {
console.error('Error fetching collections:', err);
setError(err instanceof Error ? err.message : 'Failed to load collections');
} finally {
setLoading(false);
}
}, [first]);
useEffect(() => {
fetchCollections();
}, [fetchCollections]);
return { collections, loading, error, refetch: fetchCollections };
}
// Hook for fetching products in a collection
export function useCollectionProducts(
handle: string | null,
options: UseCollectionProductsOptions = {}
) {
const [collection, setCollection] = useState<CollectionWithProducts | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchCollection = useCallback(async () => {
if (!handle) {
setLoading(false);
return;
}
try {
setLoading(true);
setError(null);
const data = await getCollectionProducts(handle, options);
setCollection(data);
if (!data) {
setError('Collection not found');
}
} catch (err) {
console.error('Error fetching collection products:', err);
setError(err instanceof Error ? err.message : 'Failed to load collection');
} finally {
setLoading(false);
}
}, [handle, options.first, options.sortKey, options.reverse]);
useEffect(() => {
fetchCollection();
}, [fetchCollection]);
return { collection, loading, error, refetch: fetchCollection };
}
+205
View File
@@ -0,0 +1,205 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { shopifyFetch } from '@/services/shopify/client';
import {
GET_PRODUCTS_QUERY,
GET_PRODUCT_QUERY,
QUERY_PRODUCT_RECOMMENDATIONS,
} from '@/graphql/products';
interface ProductImage {
url: string;
altText?: string;
}
interface ProductPrice {
amount: string;
currencyCode: string;
}
interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
selectedOptions: Array<{
name: string;
value: string;
}>;
image?: ProductImage;
}
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[];
}
interface UseProductsOptions {
first?: number;
query?: string;
sortKey?: 'BEST_SELLING' | 'CREATED_AT' | 'PRICE' | 'TITLE';
reverse?: boolean;
}
interface UseProductsReturn {
products: Product[];
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
}
// Fetch multiple products
export async function getProducts({
first = 20,
query = '',
sortKey = 'BEST_SELLING',
reverse = false,
}: UseProductsOptions = {}): Promise<Product[]> {
const response = await shopifyFetch({
query: GET_PRODUCTS_QUERY,
variables: { first, query, sortKey, reverse },
});
return response.data.products.edges.map((edge: { node: Product }) => edge.node);
}
// Fetch a single product by handle
export async function getProduct(handle: string): Promise<Product | null> {
const response = await shopifyFetch({
query: GET_PRODUCT_QUERY,
variables: { handle },
});
return response.data.product;
}
// Fetch product recommendations
export async function getProductRecommendations(productId: string): Promise<Product[]> {
const response = await shopifyFetch({
query: QUERY_PRODUCT_RECOMMENDATIONS,
variables: { productId },
});
return response.data.productRecommendations || [];
}
// Hook for fetching multiple products
export function useProducts(options: UseProductsOptions = {}): UseProductsReturn {
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchProducts = useCallback(async () => {
try {
setLoading(true);
setError(null);
const data = await getProducts(options);
setProducts(data);
} catch (err) {
console.error('Error fetching products:', err);
setError(err instanceof Error ? err.message : 'Failed to load products');
} finally {
setLoading(false);
}
}, [options.first, options.query, options.sortKey, options.reverse]);
useEffect(() => {
fetchProducts();
}, [fetchProducts]);
return { products, loading, error, refetch: fetchProducts };
}
// Hook for fetching a single product
export function useProduct(handle: string | null) {
const [product, setProduct] = useState<Product | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchProduct = useCallback(async () => {
if (!handle) {
setLoading(false);
return;
}
try {
setLoading(true);
setError(null);
const data = await getProduct(handle);
setProduct(data);
if (!data) {
setError('Product not found');
}
} catch (err) {
console.error('Error fetching product:', err);
setError(err instanceof Error ? err.message : 'Failed to load product');
} finally {
setLoading(false);
}
}, [handle]);
useEffect(() => {
fetchProduct();
}, [fetchProduct]);
return { product, loading, error, refetch: fetchProduct };
}
// Hook for fetching product recommendations
export function useProductRecommendations(productId: string | null) {
const [recommendations, setRecommendations] = useState<Product[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchRecommendations = useCallback(async () => {
if (!productId) {
setLoading(false);
return;
}
try {
setLoading(true);
setError(null);
const data = await getProductRecommendations(productId);
setRecommendations(data);
} catch (err) {
console.error('Error fetching recommendations:', err);
setError(err instanceof Error ? err.message : 'Failed to load recommendations');
} finally {
setLoading(false);
}
}, [productId]);
useEffect(() => {
fetchRecommendations();
}, [fetchRecommendations]);
return { recommendations, loading, error, refetch: fetchRecommendations };
}
+1
View File
@@ -0,0 +1 @@
export function register() {}
+7
View File
@@ -0,0 +1,7 @@
// Server-only config for the Frontend Cloud proxy routes.
// The API key lives here (read from a non-public env var) so it is never
// shipped to the browser bundle.
export const CLOUD_BASE = "https://cloud.frontend.co";
export const FRONTEND_API_KEY = process.env.FRONTEND_API_KEY ?? "";
+12
View File
@@ -0,0 +1,12 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function truncate(str: string, maxLength: number): string {
if (!str) return '';
if (str.length <= maxLength) return str;
return str.slice(0, maxLength).trim() + '...';
}
+33
View File
@@ -0,0 +1,33 @@
export default {
reactStrictMode: true,
typescript: {
ignoreBuildErrors: true,
},
images: {
unoptimized: true,
remotePatterns: [
{
protocol: 'https',
hostname: 'images.unsplash.com',
},
{
protocol: 'https',
hostname: 'cdn.shopify.com',
},
{
protocol: 'https',
hostname: '**.frontend.co',
},
],
},
experimental: {
reactDebugChannel: false
},
webpack: (config, { isServer }) => {
config.cache = { type: "memory" };
if (isServer) {
config.optimization = config.optimization || {};
config.optimization.splitChunks = false;
} return config;
}
};
+40
View File
@@ -0,0 +1,40 @@
{
"name": "nextjs-app",
"type": "module",
"private": true,
"scripts": {
"dev": "next dev --webpack",
"build": "next build --webpack",
"start": "next start"
},
"version": "0.0.0",
"dependencies": {
"@next/swc-wasm-web": "16.2.10",
"@remixicon/react": "^4.9.0",
"@shopify/storefront-api-client": "^1.0.0",
"@supabase/supabase-js": "^2.51.0",
"class-variance-authority": "0.7.1",
"clsx": "^2.1.1",
"embla-carousel-react": "^8.6.0",
"framer-motion": "12.42.2",
"input-otp": "^1.4.2",
"lucide-react": "^0.562.0",
"motion": "^12.23.26",
"next": "16.2.10",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"tailwindcss": "^4",
"tw-animate-css": "1.4.0",
"zustand": "^5.0.11"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^22",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5.7.3"
},
"packageManager": "yarn@4.18.0+sha512.fcb8716fe7cd0eece141ffc18b92193a9df9204c1ba83189c288835223fc0bbe64af473bab0d5e9927a7daeb5caf2bb07eb2787cc9338ca040ea125f2a1f2f7e"
}
+5
View File
@@ -0,0 +1,5 @@
export default {
plugins: {
'@tailwindcss/postcss': {}
}
};
+48
View File
@@ -0,0 +1,48 @@
// Shopify Storefront API Service
const SHOPIFY_STORE_DOMAIN = process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN;
const SHOPIFY_STOREFRONT_ACCESS_TOKEN = process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN;
const SHOPIFY_API_VERSION = process.env.NEXT_PUBLIC_SHOPIFY_API_VERSION || '2025-07';
const SHOPIFY_STOREFRONT_API_URL = `https://${SHOPIFY_STORE_DOMAIN}/api/${SHOPIFY_API_VERSION}/graphql.json`;
// Shopify API request with optional access token
async function shopifyFetch({ query, variables = {} }) {
try {
const headers = {
'Content-Type': 'application/json',
};
// Add access token if available
if (SHOPIFY_STOREFRONT_ACCESS_TOKEN) {
headers['X-Shopify-Storefront-Access-Token'] = SHOPIFY_STOREFRONT_ACCESS_TOKEN;
}
const response = await fetch(SHOPIFY_STOREFRONT_API_URL, {
method: 'POST',
headers,
body: JSON.stringify({
query,
variables,
}),
cache: 'no-store', // Ensure fresh data for cart operations
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Shopify API HTTP error! Status: ${response.status}, Body: ${errorBody}`);
}
const json = await response.json();
if (json.errors) {
console.error('Shopify API errors:', json.errors);
throw new Error(`Shopify GraphQL errors: ${JSON.stringify(json.errors)}`);
}
return json;
} catch (error) {
console.error('Shopify fetch error:', error);
throw error;
}
}
export { shopifyFetch, SHOPIFY_STORE_DOMAIN, SHOPIFY_STOREFRONT_API_URL };
+41
View File
@@ -0,0 +1,41 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
+1401
View File
File diff suppressed because it is too large Load Diff