chore: working on migrating to rapyd from shopify

This commit is contained in:
Gunnar Torfi 2025-03-15 11:15:46 +00:00
parent 5f4b245ea7
commit 31b46232b0
54 changed files with 1913 additions and 2229 deletions

View File

@ -1,9 +1,44 @@
import OpengraphImage from 'components/opengraph-image';
import { getPage } from 'lib/shopify';
import { getPage } from "lib/store/pages";
import { ImageResponse } from "next/og";
export const runtime = "edge";
export const contentType = "image/png";
export const size = {
width: 1200,
height: 630,
};
export default async function Image({ params }: { params: { page: string } }) {
const page = await getPage(params.page);
const title = page.seo?.title || page.title;
const title = page?.seo?.title || page?.title || "Page Not Found";
return await OpengraphImage({ title });
return new ImageResponse(
(
<div
style={{
background: "white",
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 48,
}}
>
<div
style={{
fontSize: 48,
fontWeight: 600,
textAlign: "center",
color: "black",
}}
>
{title}
</div>
</div>
),
{
...size,
}
);
}

View File

@ -1,13 +1,14 @@
import type { Metadata } from 'next';
import type { Metadata } from "next";
import Prose from 'components/prose';
import { getPage } from 'lib/shopify';
import { notFound } from 'next/navigation';
import Prose from "components/prose";
import { getPage } from "lib/store/pages";
import { notFound } from "next/navigation";
export async function generateMetadata(props: {
params: Promise<{ page: string }>;
export async function generateMetadata({
params,
}: {
params: { page: string };
}): Promise<Metadata> {
const params = await props.params;
const page = await getPage(params.page);
if (!page) return notFound();
@ -18,13 +19,12 @@ export async function generateMetadata(props: {
openGraph: {
publishedTime: page.createdAt,
modifiedTime: page.updatedAt,
type: 'article'
}
type: "article",
},
};
}
export default async function Page(props: { params: Promise<{ page: string }> }) {
const params = await props.params;
export default async function Page({ params }: { params: { page: string } }) {
const page = await getPage(params.page);
if (!page) return notFound();
@ -34,11 +34,14 @@ export default async function Page(props: { params: Promise<{ page: string }> })
<h1 className="mb-8 text-5xl font-bold">{page.title}</h1>
<Prose className="mb-8" html={page.body} />
<p className="text-sm italic">
{`This document was last updated on ${new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric'
}).format(new Date(page.updatedAt))}.`}
{`This document was last updated on ${new Intl.DateTimeFormat(
undefined,
{
year: "numeric",
month: "long",
day: "numeric",
}
).format(new Date(page.updatedAt))}.`}
</p>
</>
);

View File

@ -1,6 +1,23 @@
import { revalidate } from 'lib/shopify';
import { NextRequest, NextResponse } from 'next/server';
import { revalidateTag } from "next/cache";
import { NextRequest, NextResponse } from "next/server";
export const runtime = "edge";
export async function POST(req: NextRequest): Promise<NextResponse> {
return revalidate(req);
try {
const body = await req.json();
const tag = body.tag;
if (!tag) {
return NextResponse.json(
{ message: "Missing tag param" },
{ status: 400 }
);
}
revalidateTag(tag);
return NextResponse.json({ revalidated: true, now: Date.now() });
} catch (error) {
return NextResponse.json({ message: "Invalid JSON" }, { status: 400 });
}
}

View File

@ -30,7 +30,7 @@ export const CheckoutButton = ({
description,
});
if (!result.success) {
if (!result.success || !result.data?.redirect_url) {
toast.error("Failed to create checkout session");
return;
}

View File

@ -1,8 +1,12 @@
@import 'tailwindcss';
@custom-variant dark (&:is(.dark *));
@plugin "@tailwindcss/container-queries";
@plugin "@tailwindcss/typography";
@plugin 'tailwindcss-animate';
@layer base {
*,
::after,
@ -30,3 +34,119 @@ input,
button {
@apply focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-neutral-400 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-50 dark:focus-visible:ring-neutral-600 dark:focus-visible:ring-offset-neutral-900;
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

View File

@ -1,46 +1,19 @@
import { CartProvider } from 'components/cart/cart-context';
import { Navbar } from 'components/layout/navbar';
import { WelcomeToast } from 'components/welcome-toast';
import { GeistSans } from 'geist/font/sans';
import { getCart } from 'lib/shopify';
import { ReactNode } from 'react';
import { Toaster } from 'sonner';
import './globals.css';
import { baseUrl } from 'lib/utils';
import { CartProvider } from "components/cart/cart-context";
import { Inter } from "next/font/google";
import { ReactNode } from "react";
import "./globals.css";
const { SITE_NAME } = process.env;
export const metadata = {
metadataBase: new URL(baseUrl),
title: {
default: SITE_NAME!,
template: `%s | ${SITE_NAME}`
},
robots: {
follow: true,
index: true
}
};
const inter = Inter({ subsets: ["latin"] });
export default async function RootLayout({
children
children,
}: {
children: ReactNode;
}) {
// Don't await the fetch, pass the Promise to the context provider
const cart = getCart();
return (
<html lang="en" className={GeistSans.variable}>
<body className="bg-neutral-50 text-black selection:bg-teal-300 dark:bg-neutral-900 dark:text-white dark:selection:bg-pink-500 dark:selection:text-white">
<CartProvider cartPromise={cart}>
<Navbar />
<main>
{children}
<Toaster closeButton />
<WelcomeToast />
</main>
</CartProvider>
<html lang="en">
<body className={inter.className}>
<CartProvider>{children}</CartProvider>
</body>
</html>
);

View File

@ -1,20 +1,18 @@
import { Carousel } from 'components/carousel';
import { ThreeItemGrid } from 'components/grid/three-items';
import Footer from 'components/layout/footer';
import Footer from "components/layout/footer";
import { MainProductCard } from "components/product/main-product-card";
export const metadata = {
description:
'High-performance ecommerce store built with Next.js, Vercel, and Shopify.',
"High-performance ecommerce store built with Next.js, Vercel, and Shopify.",
openGraph: {
type: 'website'
}
type: "website",
},
};
export default function HomePage() {
return (
<>
<ThreeItemGrid />
<Carousel />
<MainProductCard />
<Footer />
</>
);

View File

@ -1,26 +1,26 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { GridTileImage } from 'components/grid/tile';
import Footer from 'components/layout/footer';
import { Gallery } from 'components/product/gallery';
import { ProductProvider } from 'components/product/product-context';
import { ProductDescription } from 'components/product/product-description';
import { HIDDEN_PRODUCT_TAG } from 'lib/constants';
import { getProduct, getProductRecommendations } from 'lib/shopify';
import { Image } from 'lib/shopify/types';
import Link from 'next/link';
import { Suspense } from 'react';
import { GridTileImage } from "components/grid/tile";
import Footer from "components/layout/footer";
import { Gallery } from "components/product/gallery";
import { ProductProvider } from "components/product/product-context";
import { ProductDescription } from "components/product/product-description";
import { HIDDEN_PRODUCT_TAG } from "lib/constants";
import { getProduct, getProductRecommendations } from "lib/store/products";
import { getImageUrl } from "lib/utils/image";
import Link from "next/link";
import { Suspense } from "react";
export async function generateMetadata(props: {
params: Promise<{ handle: string }>;
}): Promise<Metadata> {
const params = await props.params;
const product = await getProduct(params.handle);
const product = await getProduct({ handle: params.handle });
if (!product) return notFound();
const { url, width, height, altText: alt } = product.featuredImage || {};
const { source, width, height, altText: alt } = product.featuredImage || {};
const indexable = !product.tags.includes(HIDDEN_PRODUCT_TAG);
return {
@ -31,45 +31,47 @@ export async function generateMetadata(props: {
follow: indexable,
googleBot: {
index: indexable,
follow: indexable
}
follow: indexable,
},
},
openGraph: url
openGraph: source
? {
images: [
{
url,
url: getImageUrl(source),
width,
height,
alt
}
]
alt,
},
],
}
: null
: null,
};
}
export default async function ProductPage(props: { params: Promise<{ handle: string }> }) {
export default async function ProductPage(props: {
params: Promise<{ handle: string }>;
}) {
const params = await props.params;
const product = await getProduct(params.handle);
const product = await getProduct({ handle: params.handle });
if (!product) return notFound();
const productJsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
"@context": "https://schema.org",
"@type": "Product",
name: product.title,
description: product.description,
image: product.featuredImage.url,
image: getImageUrl(product.featuredImage.source),
offers: {
'@type': 'AggregateOffer',
"@type": "AggregateOffer",
availability: product.availableForSale
? 'https://schema.org/InStock'
: 'https://schema.org/OutOfStock',
? "https://schema.org/InStock"
: "https://schema.org/OutOfStock",
priceCurrency: product.priceRange.minVariantPrice.currencyCode,
highPrice: product.priceRange.maxVariantPrice.amount,
lowPrice: product.priceRange.minVariantPrice.amount
}
lowPrice: product.priceRange.minVariantPrice.amount,
},
};
return (
@ -77,7 +79,7 @@ export default async function ProductPage(props: { params: Promise<{ handle: str
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(productJsonLd)
__html: JSON.stringify(productJsonLd),
}}
/>
<div className="mx-auto max-w-(--breakpoint-2xl) px-4">
@ -88,12 +90,7 @@ export default async function ProductPage(props: { params: Promise<{ handle: str
<div className="relative aspect-square h-full max-h-[550px] w-full overflow-hidden" />
}
>
<Gallery
images={product.images.slice(0, 5).map((image: Image) => ({
src: image.url,
altText: image.altText
}))}
/>
<Gallery images={product.images} />
</Suspense>
</div>
@ -111,7 +108,7 @@ export default async function ProductPage(props: { params: Promise<{ handle: str
}
async function RelatedProducts({ id }: { id: string }) {
const relatedProducts = await getProductRecommendations(id);
const relatedProducts = await getProductRecommendations({ productId: id });
if (!relatedProducts.length) return null;
@ -134,9 +131,13 @@ async function RelatedProducts({ id }: { id: string }) {
label={{
title: product.title,
amount: product.priceRange.maxVariantPrice.amount,
currencyCode: product.priceRange.maxVariantPrice.currencyCode
currencyCode: product.priceRange.maxVariantPrice.currencyCode,
}}
src={product.featuredImage?.url}
src={
product.featuredImage
? getImageUrl(product.featuredImage.source)
: ""
}
fill
sizes="(min-width: 1024px) 20vw, (min-width: 768px) 25vw, (min-width: 640px) 33vw, (min-width: 475px) 50vw, 100vw"
/>

View File

@ -1,13 +1,49 @@
import OpengraphImage from 'components/opengraph-image';
import { getCollection } from 'lib/shopify';
import { getCollections } from "lib/store/products";
import { ImageResponse } from "next/og";
export const runtime = "edge";
export const contentType = "image/png";
export const size = {
width: 1200,
height: 630,
};
export default async function Image({
params
params,
}: {
params: { collection: string };
}) {
const collection = await getCollection(params.collection);
const title = collection?.seo?.title || collection?.title;
const collections = await getCollections();
const collection = collections.find((c) => c.handle === params.collection);
const title = collection?.title || "Collection Not Found";
return await OpengraphImage({ title });
return new ImageResponse(
(
<div
style={{
background: "white",
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 48,
}}
>
<div
style={{
fontSize: 48,
fontWeight: 600,
textAlign: "center",
color: "black",
}}
>
{title}
</div>
</div>
),
{
...size,
}
);
}

View File

@ -1,25 +1,17 @@
import { getCollection, getCollectionProducts } from 'lib/shopify';
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Grid from "components/grid";
import ProductGridItems from "components/layout/product-grid-items";
import { getCollectionProducts } from "lib/store/products";
import { Metadata } from "next";
import Grid from 'components/grid';
import ProductGridItems from 'components/layout/product-grid-items';
import { defaultSort, sorting } from 'lib/constants';
const defaultSort = {
sortKey: "RELEVANCE",
reverse: false,
};
export async function generateMetadata(props: {
params: Promise<{ collection: string }>;
}): Promise<Metadata> {
const params = await props.params;
const collection = await getCollection(params.collection);
if (!collection) return notFound();
return {
title: collection.seo?.title || collection.title,
description:
collection.seo?.description || collection.description || `${collection.title} products`
};
}
export const metadata: Metadata = {
title: "Search",
description: "Search the collection.",
};
export default async function CategoryPage(props: {
params: Promise<{ collection: string }>;
@ -28,8 +20,12 @@ export default async function CategoryPage(props: {
const searchParams = await props.searchParams;
const params = await props.params;
const { sort } = searchParams as { [key: string]: string };
const { sortKey, reverse } = sorting.find((item) => item.slug === sort) || defaultSort;
const products = await getCollectionProducts({ collection: params.collection, sortKey, reverse });
const { sortKey, reverse } = defaultSort;
const products = await getCollectionProducts({
collection: params.collection,
sortKey,
reverse,
});
return (
<section>

View File

@ -1,11 +1,16 @@
import Grid from 'components/grid';
import ProductGridItems from 'components/layout/product-grid-items';
import { defaultSort, sorting } from 'lib/constants';
import { getProducts } from 'lib/shopify';
import Grid from "components/grid";
import ProductGridItems from "components/layout/product-grid-items";
import { getProducts } from "lib/store/products";
import { Metadata } from "next";
export const metadata = {
title: 'Search',
description: 'Search for products in the store.'
export const metadata: Metadata = {
title: "Search",
description: "Search for products in the store.",
};
const defaultSort = {
sortKey: "RELEVANCE",
reverse: false,
};
export default async function SearchPage(props: {
@ -13,17 +18,17 @@ export default async function SearchPage(props: {
}) {
const searchParams = await props.searchParams;
const { sort, q: searchValue } = searchParams as { [key: string]: string };
const { sortKey, reverse } = sorting.find((item) => item.slug === sort) || defaultSort;
const { sortKey, reverse } = defaultSort;
const products = await getProducts({ sortKey, reverse, query: searchValue });
const resultsText = products.length > 1 ? 'results' : 'result';
const resultsText = products.length > 1 ? "results" : "result";
return (
<>
{searchValue ? (
<p className="mb-4">
{products.length === 0
? 'There are no products that match '
? "There are no products that match "
: `Showing ${products.length} ${resultsText} for `}
<span className="font-bold">&quot;{searchValue}&quot;</span>
</p>

View File

@ -1,52 +1,21 @@
import { getCollections, getPages, getProducts } from 'lib/shopify';
import { baseUrl, validateEnvironmentVariables } from 'lib/utils';
import { MetadataRoute } from 'next';
type Route = {
url: string;
lastModified: string;
};
export const dynamic = 'force-dynamic';
import { getCollections, getProducts } from "lib/store/products";
import { MetadataRoute } from "next";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
validateEnvironmentVariables();
const products = await getProducts();
const collections = await getCollections();
const routesMap = [''].map((route) => ({
url: `${baseUrl}${route}`,
lastModified: new Date().toISOString()
const productUrls = products.map((product) => ({
url: `${process.env.NEXT_PUBLIC_URL}/product/${product.handle}`,
lastModified: product.updatedAt,
}));
const collectionsPromise = getCollections().then((collections) =>
collections.map((collection) => ({
url: `${baseUrl}${collection.path}`,
lastModified: collection.updatedAt
}))
);
const collectionUrls = collections.map((collection) => ({
url: `${process.env.NEXT_PUBLIC_URL}/search/${collection.handle}`,
lastModified: collection.updatedAt,
}));
const productsPromise = getProducts({}).then((products) =>
products.map((product) => ({
url: `${baseUrl}/product/${product.handle}`,
lastModified: product.updatedAt
}))
);
const urls = [...productUrls, ...collectionUrls];
const pagesPromise = getPages().then((pages) =>
pages.map((page) => ({
url: `${baseUrl}/${page.handle}`,
lastModified: page.updatedAt
}))
);
let fetchedRoutes: Route[] = [];
try {
fetchedRoutes = (
await Promise.all([collectionsPromise, productsPromise, pagesPromise])
).flat();
} catch (error) {
throw JSON.stringify(error, null, 2);
}
return [...routesMap, ...fetchedRoutes];
return urls;
}

21
components.json Normal file
View File

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@ -1,10 +1,13 @@
import { getCollectionProducts } from 'lib/shopify';
import Link from 'next/link';
import { GridTileImage } from './grid/tile';
import { getCollectionProducts } from "lib/store/products";
import { getImageUrl } from "lib/utils/image";
import Link from "next/link";
import { GridTileImage } from "./grid/tile";
export async function Carousel() {
// Collections that start with `hidden-*` are hidden from the search page.
const products = await getCollectionProducts({ collection: 'hidden-homepage-carousel' });
const products = await getCollectionProducts({
collection: "hidden-homepage-carousel",
});
if (!products?.length) return null;
@ -19,15 +22,22 @@ export async function Carousel() {
key={`${product.handle}${i}`}
className="relative aspect-square h-[30vh] max-h-[275px] w-2/3 max-w-[475px] flex-none md:w-1/3"
>
<Link href={`/product/${product.handle}`} className="relative h-full w-full">
<Link
href={`/product/${product.handle}`}
className="relative h-full w-full"
>
<GridTileImage
alt={product.title}
label={{
title: product.title,
amount: product.priceRange.maxVariantPrice.amount,
currencyCode: product.priceRange.maxVariantPrice.currencyCode
currencyCode: product.priceRange.maxVariantPrice.currencyCode,
}}
src={product.featuredImage?.url}
src={
product.featuredImage
? getImageUrl(product.featuredImage.source)
: ""
}
fill
sizes="(min-width: 1024px) 25vw, (min-width: 768px) 33vw, 50vw"
/>

View File

@ -1,106 +1,128 @@
'use server';
"use server";
import { TAGS } from 'lib/constants';
import {
addToCart,
createCart,
getCart,
removeFromCart,
updateCart
} from 'lib/shopify';
import { revalidateTag } from 'next/cache';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { TAGS } from "lib/constants";
import { revalidateTag } from "next/cache";
import { RequestCookies } from "next/dist/server/web/spec-extension/cookies";
import { cookies } from "next/headers";
export async function addItem(
prevState: any,
selectedVariantId: string | undefined
) {
export interface CartItem {
id: string;
quantity: number;
}
const CART_COOKIE = "cart";
const getCartFromCookie = (): CartItem[] => {
const cookieStore = cookies() as unknown as RequestCookies;
const cartCookie = cookieStore.get(CART_COOKIE)?.value;
return cartCookie ? JSON.parse(cartCookie) : [];
};
const setCartCookie = (cart: CartItem[]) => {
const cookieStore = cookies() as unknown as RequestCookies;
cookieStore.set(CART_COOKIE, JSON.stringify(cart));
};
export const addToCart = async (productId: string) => {
const cart = getCartFromCookie();
const existingItem = cart.find((item) => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
cart.push({ id: productId, quantity: 1 });
}
setCartCookie(cart);
return cart;
};
export const removeFromCart = async (productId: string) => {
const cart = getCartFromCookie();
const updatedCart = cart.filter((item) => item.id !== productId);
setCartCookie(updatedCart);
return updatedCart;
};
export const updateCartItemQuantity = async (
productId: string,
quantity: number
) => {
const cart = getCartFromCookie();
const item = cart.find((item) => item.id === productId);
if (item) {
item.quantity = quantity;
}
const updatedCart = cart.filter((item) => item.quantity > 0);
setCartCookie(updatedCart);
return updatedCart;
};
export const getCart = async (): Promise<CartItem[]> => {
return getCartFromCookie();
};
export async function addItem(selectedVariantId: string | undefined) {
if (!selectedVariantId) {
return 'Error adding item to cart';
return "Missing product variant ID";
}
try {
await addToCart([{ merchandiseId: selectedVariantId, quantity: 1 }]);
await addToCart(selectedVariantId);
revalidateTag(TAGS.cart);
} catch (e) {
return 'Error adding item to cart';
return "Error adding item to cart";
}
}
export async function removeItem(prevState: any, merchandiseId: string) {
export async function removeItem(merchandiseId: string | undefined) {
if (!merchandiseId) {
return "Missing product ID";
}
try {
const cart = await getCart();
if (!cart) {
return 'Error fetching cart';
}
const lineItem = cart.find((line) => line.id === merchandiseId);
const lineItem = cart.lines.find(
(line) => line.merchandise.id === merchandiseId
);
if (lineItem && lineItem.id) {
await removeFromCart([lineItem.id]);
if (lineItem) {
await removeFromCart(merchandiseId);
revalidateTag(TAGS.cart);
} else {
return 'Item not found in cart';
return "Item not found in cart";
}
} catch (e) {
return 'Error removing item from cart';
return "Error removing item from cart";
}
}
export async function updateItemQuantity(
prevState: any,
payload: {
merchandiseId: string;
quantity: number;
}
merchandiseId: string | undefined,
quantity: number
) {
const { merchandiseId, quantity } = payload;
if (!merchandiseId) {
return "Missing product ID";
}
try {
const cart = await getCart();
if (!cart) {
return 'Error fetching cart';
}
const lineItem = cart.find((line) => line.id === merchandiseId);
const lineItem = cart.lines.find(
(line) => line.merchandise.id === merchandiseId
);
if (lineItem && lineItem.id) {
if (lineItem) {
if (quantity === 0) {
await removeFromCart([lineItem.id]);
await removeFromCart(merchandiseId);
} else {
await updateCart([
{
id: lineItem.id,
merchandiseId,
quantity
}
]);
await updateCartItemQuantity(merchandiseId, quantity);
}
} else if (quantity > 0) {
// If the item doesn't exist in the cart and quantity > 0, add it
await addToCart([{ merchandiseId, quantity }]);
await addToCart(merchandiseId);
}
revalidateTag(TAGS.cart);
} catch (e) {
console.error(e);
return 'Error updating item quantity';
return "Error updating item quantity";
}
}
export async function redirectToCheckout() {
let cart = await getCart();
redirect(cart!.checkoutUrl);
}
export async function createCartAndSetCookie() {
let cart = await createCart();
(await cookies()).set('cartId', cart.id!);
}

View File

@ -1,23 +1,23 @@
'use client';
"use client";
import { PlusIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
import { addItem } from 'components/cart/actions';
import { useProduct } from 'components/product/product-context';
import { Product, ProductVariant } from 'lib/shopify/types';
import { useActionState } from 'react';
import { useCart } from './cart-context';
import { PlusIcon } from "@heroicons/react/24/outline";
import clsx from "clsx";
import { addItem } from "components/cart/actions";
import { useProduct } from "components/product/product-context";
import { Product, ProductVariant } from "lib/store/types";
import { useActionState } from "react";
import { useCart } from "./cart-context";
function SubmitButton({
availableForSale,
selectedVariantId
selectedVariantId,
}: {
availableForSale: boolean;
selectedVariantId: string | undefined;
}) {
const buttonClasses =
'relative flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white';
const disabledClasses = 'cursor-not-allowed opacity-60 hover:opacity-60';
"relative flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white";
const disabledClasses = "cursor-not-allowed opacity-60 hover:opacity-60";
if (!availableForSale) {
return (
@ -46,7 +46,7 @@ function SubmitButton({
<button
aria-label="Add to cart"
className={clsx(buttonClasses, {
'hover:opacity-90': true
"hover:opacity-90": true,
})}
>
<div className="absolute left-0 ml-4">
@ -61,7 +61,10 @@ export function AddToCart({ product }: { product: Product }) {
const { variants, availableForSale } = product;
const { addCartItem } = useCart();
const { state } = useProduct();
const [message, formAction] = useActionState(addItem, null);
const [message, formAction] = useActionState(
addItem,
"Error adding item to cart"
);
const variant = variants.find((variant: ProductVariant) =>
variant.selectedOptions.every(
@ -75,6 +78,13 @@ export function AddToCart({ product }: { product: Product }) {
(variant) => variant.id === selectedVariantId
)!;
console.log({
variant,
defaultVariantId,
selectedVariantId,
product,
});
return (
<form
action={async () => {

View File

@ -1,204 +1,223 @@
'use client';
"use client";
import type {
Cart,
CartItem,
Product,
ProductVariant
} from 'lib/shopify/types';
import React, {
createContext,
use,
useContext,
useMemo,
useOptimistic
} from 'react';
import { Product, ProductVariant } from "lib/store/types";
import { createContext, useContext, useState } from "react";
type UpdateType = 'plus' | 'minus' | 'delete';
type CartItem = {
merchandise: ProductVariant & {
product: Product;
};
quantity: number;
};
type CartAction =
| {
type: 'UPDATE_ITEM';
payload: { merchandiseId: string; updateType: UpdateType };
}
| {
type: 'ADD_ITEM';
payload: { variant: ProductVariant; product: Product };
type CartState = {
lines: CartItem[];
totalQuantity: number;
cost: {
subtotalAmount: {
amount: string;
currencyCode: string;
};
totalAmount: {
amount: string;
currencyCode: string;
};
totalTaxAmount: {
amount: string;
currencyCode: string;
};
};
};
type CartContextType = {
cartPromise: Promise<Cart | undefined>;
cart: CartState;
addCartItem: (variant: ProductVariant, product: Product) => void;
removeCartItem: (variantId: string) => void;
updateCartItem: (variantId: string, quantity: number) => void;
};
const CartContext = createContext<CartContextType | undefined>(undefined);
function calculateItemCost(quantity: number, price: string): string {
return (Number(price) * quantity).toString();
}
function updateCartItem(
item: CartItem,
updateType: UpdateType
): CartItem | null {
if (updateType === 'delete') return null;
const newQuantity =
updateType === 'plus' ? item.quantity + 1 : item.quantity - 1;
if (newQuantity === 0) return null;
const singleItemAmount = Number(item.cost.totalAmount.amount) / item.quantity;
const newTotalAmount = calculateItemCost(
newQuantity,
singleItemAmount.toString()
);
return {
...item,
quantity: newQuantity,
cost: {
...item.cost,
totalAmount: {
...item.cost.totalAmount,
amount: newTotalAmount
}
}
};
}
function createOrUpdateCartItem(
existingItem: CartItem | undefined,
variant: ProductVariant,
product: Product
): CartItem {
const quantity = existingItem ? existingItem.quantity + 1 : 1;
const totalAmount = calculateItemCost(quantity, variant.price.amount);
return {
id: existingItem?.id,
quantity,
cost: {
totalAmount: {
amount: totalAmount,
currencyCode: variant.price.currencyCode
}
},
merchandise: {
id: variant.id,
title: variant.title,
selectedOptions: variant.selectedOptions,
product: {
id: product.id,
handle: product.handle,
title: product.title,
featuredImage: product.featuredImage
}
}
};
}
function updateCartTotals(
lines: CartItem[]
): Pick<Cart, 'totalQuantity' | 'cost'> {
const totalQuantity = lines.reduce((sum, item) => sum + item.quantity, 0);
const totalAmount = lines.reduce(
(sum, item) => sum + Number(item.cost.totalAmount.amount),
0
);
const currencyCode = lines[0]?.cost.totalAmount.currencyCode ?? 'USD';
return {
totalQuantity,
cost: {
subtotalAmount: { amount: totalAmount.toString(), currencyCode },
totalAmount: { amount: totalAmount.toString(), currencyCode },
totalTaxAmount: { amount: '0', currencyCode }
}
};
}
function createEmptyCart(): Cart {
return {
id: undefined,
checkoutUrl: '',
totalQuantity: 0,
export function CartProvider({ children }: { children: React.ReactNode }) {
const [cart, setCart] = useState<CartState>({
lines: [],
totalQuantity: 0,
cost: {
subtotalAmount: { amount: '0', currencyCode: 'USD' },
totalAmount: { amount: '0', currencyCode: 'USD' },
totalTaxAmount: { amount: '0', currencyCode: 'USD' }
}
};
}
subtotalAmount: {
amount: "0",
currencyCode: "USD",
},
totalAmount: {
amount: "0",
currencyCode: "USD",
},
totalTaxAmount: {
amount: "0",
currencyCode: "USD",
},
},
});
function cartReducer(state: Cart | undefined, action: CartAction): Cart {
const currentCart = state || createEmptyCart();
switch (action.type) {
case 'UPDATE_ITEM': {
const { merchandiseId, updateType } = action.payload;
const updatedLines = currentCart.lines
.map((item) =>
item.merchandise.id === merchandiseId
? updateCartItem(item, updateType)
: item
)
.filter(Boolean) as CartItem[];
if (updatedLines.length === 0) {
return {
...currentCart,
lines: [],
totalQuantity: 0,
cost: {
...currentCart.cost,
totalAmount: { ...currentCart.cost.totalAmount, amount: '0' }
}
};
}
return {
...currentCart,
...updateCartTotals(updatedLines),
lines: updatedLines
};
}
case 'ADD_ITEM': {
const { variant, product } = action.payload;
const existingItem = currentCart.lines.find(
const addCartItem = (variant: ProductVariant, product: Product) => {
setCart((prevCart) => {
const existingItem = prevCart.lines.find(
(item) => item.merchandise.id === variant.id
);
const updatedItem = createOrUpdateCartItem(
existingItem,
variant,
product
let newLines;
if (existingItem) {
newLines = prevCart.lines.map((item) =>
item.merchandise.id === variant.id
? { ...item, quantity: item.quantity + 1 }
: item
);
} else {
newLines = [
...prevCart.lines,
{
merchandise: {
...variant,
product,
},
quantity: 1,
},
];
}
const totalQuantity = newLines.reduce(
(sum, item) => sum + item.quantity,
0
);
const updatedLines = existingItem
? currentCart.lines.map((item) =>
item.merchandise.id === variant.id ? updatedItem : item
)
: [...currentCart.lines, updatedItem];
const subtotalAmount = newLines
.reduce(
(sum, item) =>
sum + parseFloat(item.merchandise.price.amount) * item.quantity,
0
)
.toFixed(2);
// For this example, we'll assume tax rate is 10%
const taxAmount = (parseFloat(subtotalAmount) * 0.1).toFixed(2);
const totalAmount = (
parseFloat(subtotalAmount) + parseFloat(taxAmount)
).toFixed(2);
return {
...currentCart,
...updateCartTotals(updatedLines),
lines: updatedLines
lines: newLines,
totalQuantity,
cost: {
subtotalAmount: {
amount: subtotalAmount,
currencyCode: "USD",
},
totalAmount: {
amount: totalAmount,
currencyCode: "USD",
},
totalTaxAmount: {
amount: taxAmount,
currencyCode: "USD",
},
},
};
}
default:
return currentCart;
}
}
});
};
const removeCartItem = (variantId: string) => {
setCart((prevCart) => {
const newLines = prevCart.lines.filter(
(item) => item.merchandise.id !== variantId
);
const totalQuantity = newLines.reduce(
(sum, item) => sum + item.quantity,
0
);
const subtotalAmount = newLines
.reduce(
(sum, item) =>
sum + parseFloat(item.merchandise.price.amount) * item.quantity,
0
)
.toFixed(2);
const taxAmount = (parseFloat(subtotalAmount) * 0.1).toFixed(2);
const totalAmount = (
parseFloat(subtotalAmount) + parseFloat(taxAmount)
).toFixed(2);
return {
lines: newLines,
totalQuantity,
cost: {
subtotalAmount: {
amount: subtotalAmount,
currencyCode: "USD",
},
totalAmount: {
amount: totalAmount,
currencyCode: "USD",
},
totalTaxAmount: {
amount: taxAmount,
currencyCode: "USD",
},
},
};
});
};
const updateCartItem = (variantId: string, quantity: number) => {
setCart((prevCart) => {
const newLines = prevCart.lines.map((item) =>
item.merchandise.id === variantId ? { ...item, quantity } : item
);
const totalQuantity = newLines.reduce(
(sum, item) => sum + item.quantity,
0
);
const subtotalAmount = newLines
.reduce(
(sum, item) =>
sum + parseFloat(item.merchandise.price.amount) * item.quantity,
0
)
.toFixed(2);
const taxAmount = (parseFloat(subtotalAmount) * 0.1).toFixed(2);
const totalAmount = (
parseFloat(subtotalAmount) + parseFloat(taxAmount)
).toFixed(2);
return {
lines: newLines,
totalQuantity,
cost: {
subtotalAmount: {
amount: subtotalAmount,
currencyCode: "USD",
},
totalAmount: {
amount: totalAmount,
currencyCode: "USD",
},
totalTaxAmount: {
amount: taxAmount,
currencyCode: "USD",
},
},
};
});
};
export function CartProvider({
children,
cartPromise
}: {
children: React.ReactNode;
cartPromise: Promise<Cart | undefined>;
}) {
return (
<CartContext.Provider value={{ cartPromise }}>
<CartContext.Provider
value={{ cart, addCartItem, removeCartItem, updateCartItem }}
>
{children}
</CartContext.Provider>
);
@ -207,32 +226,7 @@ export function CartProvider({
export function useCart() {
const context = useContext(CartContext);
if (context === undefined) {
throw new Error('useCart must be used within a CartProvider');
throw new Error("useCart must be used within a CartProvider");
}
const initialCart = use(context.cartPromise);
const [optimisticCart, updateOptimisticCart] = useOptimistic(
initialCart,
cartReducer
);
const updateCartItem = (merchandiseId: string, updateType: UpdateType) => {
updateOptimisticCart({
type: 'UPDATE_ITEM',
payload: { merchandiseId, updateType }
});
};
const addCartItem = (variant: ProductVariant, product: Product) => {
updateOptimisticCart({ type: 'ADD_ITEM', payload: { variant, product } });
};
return useMemo(
() => ({
cart: optimisticCart,
updateCartItem,
addCartItem
}),
[optimisticCart]
);
return context;
}

View File

@ -1,38 +1,28 @@
'use client';
"use client";
import { XMarkIcon } from '@heroicons/react/24/outline';
import { removeItem } from 'components/cart/actions';
import type { CartItem } from 'lib/shopify/types';
import { useActionState } from 'react';
import { XMarkIcon } from "@heroicons/react/24/outline";
import clsx from "clsx";
import { CartItem } from "lib/store/types";
export function DeleteItemButton({
item,
optimisticUpdate
onClick,
}: {
item: CartItem;
optimisticUpdate: any;
onClick: () => void;
}) {
const [message, formAction] = useActionState(removeItem, null);
const merchandiseId = item.merchandise.id;
const removeItemAction = formAction.bind(null, merchandiseId);
return (
<form
action={async () => {
optimisticUpdate(merchandiseId, 'delete');
removeItemAction();
}}
<button
aria-label="Remove cart item"
onClick={onClick}
className={clsx(
"ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-neutral-500 transition-all duration-200",
{
"hover:bg-neutral-800": true,
}
)}
>
<button
type="submit"
aria-label="Remove cart item"
className="flex h-[24px] w-[24px] items-center justify-center rounded-full bg-neutral-500"
>
<XMarkIcon className="mx-[1px] h-4 w-4 text-white dark:text-black" />
</button>
<p aria-live="polite" className="sr-only" role="status">
{message}
</p>
</form>
<XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
</button>
);
}

View File

@ -1,61 +1,38 @@
'use client';
"use client";
import { MinusIcon, PlusIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
import { updateItemQuantity } from 'components/cart/actions';
import type { CartItem } from 'lib/shopify/types';
import { useActionState } from 'react';
function SubmitButton({ type }: { type: 'plus' | 'minus' }) {
return (
<button
type="submit"
aria-label={
type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'
}
className={clsx(
'ease flex h-full min-w-[36px] max-w-[36px] flex-none items-center justify-center rounded-full p-2 transition-all duration-200 hover:border-neutral-800 hover:opacity-80',
{
'ml-auto': type === 'minus'
}
)}
>
{type === 'plus' ? (
<PlusIcon className="h-4 w-4 dark:text-neutral-500" />
) : (
<MinusIcon className="h-4 w-4 dark:text-neutral-500" />
)}
</button>
);
}
import { MinusIcon, PlusIcon } from "@heroicons/react/24/outline";
import clsx from "clsx";
import { CartItem } from "lib/store/types";
export function EditItemQuantityButton({
item,
type,
optimisticUpdate
onClick,
}: {
item: CartItem;
type: 'plus' | 'minus';
optimisticUpdate: any;
type: "plus" | "minus";
onClick: () => void;
}) {
const [message, formAction] = useActionState(updateItemQuantity, null);
const payload = {
merchandiseId: item.merchandise.id,
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
};
const updateItemQuantityAction = formAction.bind(null, payload);
return (
<form
action={async () => {
optimisticUpdate(payload.merchandiseId, type);
updateItemQuantityAction();
}}
<button
aria-label={
type === "plus" ? "Increase item quantity" : "Reduce item quantity"
}
onClick={onClick}
className={clsx(
"flex h-full min-w-[36px] max-w-[36px] items-center justify-center px-2",
{
"cursor-not-allowed": type === "minus" && item.quantity === 1,
"cursor-pointer": type === "plus" || item.quantity > 1,
}
)}
disabled={type === "minus" && item.quantity === 1}
>
<SubmitButton type={type} />
<p aria-live="polite" className="sr-only" role="status">
{message}
</p>
</form>
{type === "plus" ? (
<PlusIcon className="h-4 w-4" />
) : (
<MinusIcon className="h-4 w-4" />
)}
</button>
);
}

View File

@ -1,256 +1,310 @@
'use client';
"use client";
import clsx from 'clsx';
import { Dialog, Transition } from '@headlessui/react';
import { ShoppingCartIcon, XMarkIcon } from '@heroicons/react/24/outline';
import LoadingDots from 'components/loading-dots';
import Price from 'components/price';
import { DEFAULT_OPTION } from 'lib/constants';
import { createUrl } from 'lib/utils';
import Image from 'next/image';
import Link from 'next/link';
import { Fragment, useEffect, useRef, useState } from 'react';
import { useFormStatus } from 'react-dom';
import { createCartAndSetCookie, redirectToCheckout } from './actions';
import { useCart } from './cart-context';
import { DeleteItemButton } from './delete-item-button';
import { EditItemQuantityButton } from './edit-item-quantity-button';
import OpenCart from './open-cart';
import { Dialog, Transition } from "@headlessui/react";
import { ShoppingCartIcon, XMarkIcon } from "@heroicons/react/24/outline";
import Price from "components/price";
import { DEFAULT_OPTION } from "lib/constants";
import { createUrl } from "lib/utils";
import { getImageUrl } from "lib/utils/image";
import Image from "next/image";
import Link from "next/link";
import { Fragment, useEffect, useRef } from "react";
import { useCart } from "./cart-context";
import { EditItemQuantityButton } from "./edit-item-quantity-button";
type MerchandiseSearchParams = {
[key: string]: string;
};
export default function CartModal() {
const { cart, updateCartItem } = useCart();
const [isOpen, setIsOpen] = useState(false);
const quantityRef = useRef(cart?.totalQuantity);
const openCart = () => setIsOpen(true);
const closeCart = () => setIsOpen(false);
const { cart, updateCartItem, removeCartItem } = useCart();
const quantityRef = useRef(cart.totalQuantity);
const openCart = () => {};
const closeCart = () => {};
useEffect(() => {
if (!cart) {
createCartAndSetCookie();
// Open cart modal when quantity changes.
if (cart.totalQuantity !== quantityRef.current) {
// But only if it's not already open.
openCart();
}
}, [cart]);
useEffect(() => {
if (
cart?.totalQuantity &&
cart?.totalQuantity !== quantityRef.current &&
cart?.totalQuantity > 0
) {
if (!isOpen) {
setIsOpen(true);
}
quantityRef.current = cart?.totalQuantity;
}
}, [isOpen, cart?.totalQuantity, quantityRef]);
quantityRef.current = cart.totalQuantity;
}, [cart.totalQuantity, openCart]);
return (
<>
<button aria-label="Open cart" onClick={openCart}>
<OpenCart quantity={cart?.totalQuantity} />
<button
aria-label="Open cart"
onClick={openCart}
className="relative flex h-11 w-11 items-center justify-center rounded-md border border-neutral-200 text-black transition-colors dark:border-neutral-700 dark:text-white"
>
<ShoppingCartIcon className="h-4 transition-all ease-in-out hover:scale-110" />
{cart.totalQuantity > 0 && (
<div className="absolute right-0 top-0 -mr-2 -mt-2 h-4 w-4 rounded bg-blue-600 text-[11px] font-medium text-white">
{cart.totalQuantity}
</div>
)}
</button>
<Transition show={isOpen}>
<Transition.Root show={true} as={Fragment}>
<Dialog onClose={closeCart} className="relative z-50">
<Transition.Child
as={Fragment}
enter="transition-all ease-in-out duration-300"
enterFrom="opacity-0 backdrop-blur-none"
enterTo="opacity-100 backdrop-blur-[.5px]"
leave="transition-all ease-in-out duration-200"
leaveFrom="opacity-100 backdrop-blur-[.5px]"
leaveTo="opacity-0 backdrop-blur-none"
enter="ease-in-out duration-500"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in-out duration-500"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
<div className="fixed inset-0 bg-neutral-400/25 backdrop-blur-sm" />
</Transition.Child>
<Transition.Child
as={Fragment}
enter="transition-all ease-in-out duration-300"
enterFrom="translate-x-full"
enterTo="translate-x-0"
leave="transition-all ease-in-out duration-200"
leaveFrom="translate-x-0"
leaveTo="translate-x-full"
>
<Dialog.Panel className="fixed bottom-0 right-0 top-0 flex h-full w-full flex-col border-l border-neutral-200 bg-white/80 p-6 text-black backdrop-blur-xl md:w-[390px] dark:border-neutral-700 dark:bg-black/80 dark:text-white">
<div className="flex items-center justify-between">
<p className="text-lg font-semibold">My Cart</p>
<button aria-label="Close cart" onClick={closeCart}>
<CloseCart />
</button>
<div className="fixed inset-0 overflow-hidden">
<div className="absolute inset-0 overflow-hidden">
<div className="pointer-events-none fixed inset-y-0 right-0 flex max-w-full pl-10">
<Transition.Child
as={Fragment}
enter="transform transition ease-in-out duration-500"
enterFrom="translate-x-full"
enterTo="translate-x-0"
leave="transform transition ease-in-out duration-500"
leaveFrom="translate-x-0"
leaveTo="translate-x-full"
>
<Dialog.Panel className="pointer-events-auto w-screen max-w-md">
<div className="flex h-full flex-col overflow-y-scroll bg-white shadow-xl dark:bg-black">
<div className="flex-1 overflow-y-auto px-4 py-6 sm:px-6">
<div className="flex items-start justify-between">
<Dialog.Title className="text-lg font-medium text-black dark:text-white">
Cart
</Dialog.Title>
<div className="ml-3 flex h-7 items-center">
<button
type="button"
className="relative -m-2 p-2 text-neutral-400 hover:text-neutral-500"
onClick={closeCart}
>
<span className="absolute -inset-0.5" />
<span className="sr-only">Close panel</span>
<XMarkIcon
className="h-6 w-6"
aria-hidden="true"
/>
</button>
</div>
</div>
<div className="mt-8">
<div className="flow-root">
{cart.lines.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center space-y-1">
<ShoppingCartIcon
className="w-16"
aria-hidden="true"
/>
<p className="text-sm font-medium text-black dark:text-white">
Your cart is empty.
</p>
</div>
) : (
<ul
role="list"
className="-my-6 divide-y divide-neutral-200"
>
{cart.lines
.sort((a, b) =>
a.merchandise.product.title.localeCompare(
b.merchandise.product.title
)
)
.map((item) => {
const merchandiseSearchParams =
{} as MerchandiseSearchParams;
item.merchandise.selectedOptions.forEach(
({ name, value }) => {
if (value !== DEFAULT_OPTION) {
merchandiseSearchParams[
name.toLowerCase()
] = value;
}
}
);
const merchandiseUrl = createUrl(
`/product/${item.merchandise.product.handle}`,
new URLSearchParams(
merchandiseSearchParams
)
);
return (
<li
key={item.merchandise.id}
className="flex py-6"
>
<div className="relative h-24 w-24 flex-shrink-0 overflow-hidden rounded-md border border-neutral-200 dark:border-neutral-800">
<Image
src={
item.merchandise.product
.featuredImage
? getImageUrl(
item.merchandise.product
.featuredImage.source
)
: ""
}
alt={item.merchandise.product.title}
className="h-full w-full object-cover object-center"
fill
/>
</div>
<div className="ml-4 flex flex-1 flex-col">
<div>
<div className="flex justify-between text-base font-medium text-black dark:text-white">
<h3>
<Link
href={merchandiseUrl}
className="font-medium"
>
{
item.merchandise.product
.title
}
</Link>
</h3>
<p className="ml-4">
<Price
amount={
item.merchandise.price
.amount
}
currencyCode={
item.merchandise.price
.currencyCode
}
/>
</p>
</div>
<p className="mt-1 text-sm text-neutral-500 dark:text-neutral-400">
{item.merchandise.title}
</p>
</div>
<div className="flex flex-1 items-end justify-between text-sm">
<div className="flex items-center border rounded-full">
<EditItemQuantityButton
item={item}
type="minus"
onClick={() => {
updateCartItem(
item.merchandise.id,
item.quantity - 1
);
}}
/>
<p className="mx-2 flex-1 text-center">
<span className="w-8">
{item.quantity}
</span>
</p>
<EditItemQuantityButton
item={item}
type="plus"
onClick={() => {
updateCartItem(
item.merchandise.id,
item.quantity + 1
);
}}
/>
</div>
<div className="ml-4">
<button
type="button"
className="text-sm font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400"
onClick={() =>
removeCartItem(
item.merchandise.id
)
}
>
Remove
</button>
</div>
</div>
</div>
</li>
);
})}
</ul>
)}
</div>
</div>
</div>
{cart.lines.length > 0 ? (
<div className="border-t border-neutral-200 px-4 py-6 sm:px-6">
<div className="flex justify-between text-base font-medium text-black dark:text-white">
<p>Subtotal</p>
<p>
<Price
amount={cart.cost.subtotalAmount.amount}
currencyCode={
cart.cost.subtotalAmount.currencyCode
}
/>
</p>
</div>
<div className="flex justify-between text-base font-medium text-black dark:text-white">
<p>Taxes</p>
<p>
<Price
amount={cart.cost.totalTaxAmount.amount}
currencyCode={
cart.cost.totalTaxAmount.currencyCode
}
/>
</p>
</div>
<div className="flex justify-between text-base font-medium text-black dark:text-white">
<p>Total</p>
<p>
<Price
amount={cart.cost.totalAmount.amount}
currencyCode={
cart.cost.totalAmount.currencyCode
}
/>
</p>
</div>
<div className="mt-6">
<button className="w-full rounded-full bg-blue-600 px-6 py-3 text-center font-medium text-white hover:bg-blue-500">
Checkout
</button>
</div>
<div className="mt-6 flex justify-center text-center text-sm text-neutral-500">
<p>
or{" "}
<button
type="button"
className="font-medium text-blue-600 hover:text-blue-500"
onClick={closeCart}
>
Continue Shopping
<span aria-hidden="true"> &rarr;</span>
</button>
</p>
</div>
</div>
) : null}
</div>
</Dialog.Panel>
</Transition.Child>
</div>
{!cart || cart.lines.length === 0 ? (
<div className="mt-20 flex w-full flex-col items-center justify-center overflow-hidden">
<ShoppingCartIcon className="h-16" />
<p className="mt-6 text-center text-2xl font-bold">
Your cart is empty.
</p>
</div>
) : (
<div className="flex h-full flex-col justify-between overflow-hidden p-1">
<ul className="grow overflow-auto py-4">
{cart.lines
.sort((a, b) =>
a.merchandise.product.title.localeCompare(
b.merchandise.product.title
)
)
.map((item, i) => {
const merchandiseSearchParams =
{} as MerchandiseSearchParams;
item.merchandise.selectedOptions.forEach(
({ name, value }) => {
if (value !== DEFAULT_OPTION) {
merchandiseSearchParams[name.toLowerCase()] =
value;
}
}
);
const merchandiseUrl = createUrl(
`/product/${item.merchandise.product.handle}`,
new URLSearchParams(merchandiseSearchParams)
);
return (
<li
key={i}
className="flex w-full flex-col border-b border-neutral-300 dark:border-neutral-700"
>
<div className="relative flex w-full flex-row justify-between px-1 py-4">
<div className="absolute z-40 -ml-1 -mt-2">
<DeleteItemButton
item={item}
optimisticUpdate={updateCartItem}
/>
</div>
<div className="flex flex-row">
<div className="relative h-16 w-16 overflow-hidden rounded-md border border-neutral-300 bg-neutral-300 dark:border-neutral-700 dark:bg-neutral-900 dark:hover:bg-neutral-800">
<Image
className="h-full w-full object-cover"
width={64}
height={64}
alt={
item.merchandise.product.featuredImage
.altText ||
item.merchandise.product.title
}
src={
item.merchandise.product.featuredImage.url
}
/>
</div>
<Link
href={merchandiseUrl}
onClick={closeCart}
className="z-30 ml-2 flex flex-row space-x-4"
>
<div className="flex flex-1 flex-col text-base">
<span className="leading-tight">
{item.merchandise.product.title}
</span>
{item.merchandise.title !==
DEFAULT_OPTION ? (
<p className="text-sm text-neutral-500 dark:text-neutral-400">
{item.merchandise.title}
</p>
) : null}
</div>
</Link>
</div>
<div className="flex h-16 flex-col justify-between">
<Price
className="flex justify-end space-y-2 text-right text-sm"
amount={item.cost.totalAmount.amount}
currencyCode={
item.cost.totalAmount.currencyCode
}
/>
<div className="ml-auto flex h-9 flex-row items-center rounded-full border border-neutral-200 dark:border-neutral-700">
<EditItemQuantityButton
item={item}
type="minus"
optimisticUpdate={updateCartItem}
/>
<p className="w-6 text-center">
<span className="w-full text-sm">
{item.quantity}
</span>
</p>
<EditItemQuantityButton
item={item}
type="plus"
optimisticUpdate={updateCartItem}
/>
</div>
</div>
</div>
</li>
);
})}
</ul>
<div className="py-4 text-sm text-neutral-500 dark:text-neutral-400">
<div className="mb-3 flex items-center justify-between border-b border-neutral-200 pb-1 dark:border-neutral-700">
<p>Taxes</p>
<Price
className="text-right text-base text-black dark:text-white"
amount={cart.cost.totalTaxAmount.amount}
currencyCode={cart.cost.totalTaxAmount.currencyCode}
/>
</div>
<div className="mb-3 flex items-center justify-between border-b border-neutral-200 pb-1 pt-1 dark:border-neutral-700">
<p>Shipping</p>
<p className="text-right">Calculated at checkout</p>
</div>
<div className="mb-3 flex items-center justify-between border-b border-neutral-200 pb-1 pt-1 dark:border-neutral-700">
<p>Total</p>
<Price
className="text-right text-base text-black dark:text-white"
amount={cart.cost.totalAmount.amount}
currencyCode={cart.cost.totalAmount.currencyCode}
/>
</div>
</div>
<form action={redirectToCheckout}>
<CheckoutButton />
</form>
</div>
)}
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
</Transition.Root>
</>
);
}
function CloseCart({ className }: { className?: string }) {
return (
<div className="relative flex h-11 w-11 items-center justify-center rounded-md border border-neutral-200 text-black transition-colors dark:border-neutral-700 dark:text-white">
<XMarkIcon
className={clsx(
'h-6 transition-all ease-in-out hover:scale-110',
className
)}
/>
</div>
);
}
function CheckoutButton() {
const { pending } = useFormStatus();
return (
<button
className="block w-full rounded-full bg-blue-600 p-3 text-center text-sm font-medium text-white opacity-90 hover:opacity-100"
type="submit"
disabled={pending}
>
{pending ? <LoadingDots className="bg-white" /> : 'Proceed to Checkout'}
</button>
);
}

View File

@ -1,20 +1,25 @@
import { GridTileImage } from 'components/grid/tile';
import { getCollectionProducts } from 'lib/shopify';
import type { Product } from 'lib/shopify/types';
import Link from 'next/link';
import { GridTileImage } from "components/grid/tile";
import { getCollectionProducts } from "lib/store/products";
import type { Product } from "lib/store/types";
import { getImageUrl } from "lib/utils/image";
import Link from "next/link";
function ThreeItemGridItem({
item,
size,
priority
priority,
}: {
item: Product;
size: 'full' | 'half';
size: "full" | "half";
priority?: boolean;
}) {
return (
<div
className={size === 'full' ? 'md:col-span-4 md:row-span-2' : 'md:col-span-2 md:row-span-1'}
className={
size === "full"
? "md:col-span-4 md:row-span-2"
: "md:col-span-2 md:row-span-1"
}
>
<Link
className="relative block aspect-square h-full w-full"
@ -22,18 +27,20 @@ function ThreeItemGridItem({
prefetch={true}
>
<GridTileImage
src={item.featuredImage.url}
src={getImageUrl(item.featuredImage.source)}
fill
sizes={
size === 'full' ? '(min-width: 768px) 66vw, 100vw' : '(min-width: 768px) 33vw, 100vw'
size === "full"
? "(min-width: 768px) 66vw, 100vw"
: "(min-width: 768px) 33vw, 100vw"
}
priority={priority}
alt={item.title}
label={{
position: size === 'full' ? 'center' : 'bottom',
position: size === "full" ? "center" : "bottom",
title: item.title as string,
amount: item.priceRange.maxVariantPrice.amount,
currencyCode: item.priceRange.maxVariantPrice.currencyCode
currencyCode: item.priceRange.maxVariantPrice.currencyCode,
}}
/>
</Link>
@ -44,7 +51,7 @@ function ThreeItemGridItem({
export async function ThreeItemGrid() {
// Collections that start with `hidden-*` are hidden from the search page.
const homepageItems = await getCollectionProducts({
collection: 'hidden-homepage-featured-items'
collection: "hidden-homepage-featured-items",
});
if (!homepageItems[0] || !homepageItems[1] || !homepageItems[2]) return null;

View File

@ -1,46 +1,30 @@
'use client';
"use client";
import clsx from 'clsx';
import { Menu } from 'lib/shopify/types';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
import clsx from "clsx";
import Link from "next/link";
export function FooterMenuItem({ item }: { item: Menu }) {
const pathname = usePathname();
const [active, setActive] = useState(pathname === item.path);
import { Menu } from "@/lib/store/menu";
useEffect(() => {
setActive(pathname === item.path);
}, [pathname, item.path]);
return (
<li>
<Link
href={item.path}
className={clsx(
'block p-2 text-lg underline-offset-4 hover:text-black hover:underline md:inline-block md:text-sm dark:hover:text-neutral-300',
{
'text-black dark:text-neutral-300': active
}
)}
>
{item.title}
</Link>
</li>
);
interface FooterMenuProps {
menu: Menu;
}
export default function FooterMenu({ menu }: { menu: Menu[] }) {
if (!menu.length) return null;
export default function FooterMenu({ menu }: FooterMenuProps) {
if (!menu.items?.length) return null;
return (
<nav>
<ul>
{menu.map((item: Menu) => {
return <FooterMenuItem key={item.title} item={item} />;
})}
</ul>
<nav className="grid grid-cols-2 gap-4 sm:grid-cols-3">
{menu.items.map((item) => (
<Link
key={item.title}
href={item.path}
className={clsx(
"text-sm text-neutral-500 underline-offset-4 hover:text-black hover:underline dark:text-neutral-400 dark:hover:text-neutral-300"
)}
>
{item.title}
</Link>
))}
</nav>
);
}

View File

@ -1,69 +1,33 @@
import Link from 'next/link';
import FooterMenu from 'components/layout/footer-menu';
import LogoSquare from 'components/logo-square';
import { getMenu } from 'lib/shopify';
import { Suspense } from 'react';
import FooterMenu from "@/components/layout/footer-menu";
import { getMenu } from "@/lib/store/menu";
const { COMPANY_NAME, SITE_NAME } = process.env;
export default async function Footer() {
const currentYear = new Date().getFullYear();
const copyrightDate = 2023 + (currentYear > 2023 ? `-${currentYear}` : '');
const skeleton = 'w-full h-6 animate-pulse rounded-sm bg-neutral-200 dark:bg-neutral-700';
const menu = await getMenu('next-js-frontend-footer-menu');
const copyrightName = COMPANY_NAME || SITE_NAME || '';
const copyrightDate = 2023 + (currentYear > 2023 ? `-${currentYear}` : "");
const skeleton =
"w-full h-6 animate-pulse rounded-sm bg-neutral-200 dark:bg-neutral-700";
const menu = await getMenu("footer");
const copyrightName = COMPANY_NAME || SITE_NAME || "";
return (
<footer className="text-sm text-neutral-500 dark:text-neutral-400">
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 border-t border-neutral-200 px-6 py-12 text-sm md:flex-row md:gap-12 md:px-4 min-[1320px]:px-0 dark:border-neutral-700">
<div>
<Link className="flex items-center gap-2 text-black md:pt-1 dark:text-white" href="/">
<LogoSquare size="sm" />
<span className="uppercase">{SITE_NAME}</span>
</Link>
<footer className="border-t border-neutral-200 bg-white text-black dark:border-neutral-700 dark:bg-black dark:text-white">
<div className="mx-auto w-full max-w-7xl px-6">
<div className="grid grid-cols-1 gap-8 border-b border-neutral-200 py-12 transition-colors duration-150 dark:border-neutral-700 md:grid-cols-3">
<div>
<h3 className="mb-4 text-sm font-bold">Shop</h3>
{menu && <FooterMenu menu={menu} />}
</div>
</div>
<Suspense
fallback={
<div className="flex h-[188px] w-[200px] flex-col gap-2">
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
</div>
}
>
<FooterMenu menu={menu} />
</Suspense>
<div className="md:ml-auto">
<a
className="flex h-8 w-max flex-none items-center justify-center rounded-md border border-neutral-200 bg-white text-xs text-black dark:border-neutral-700 dark:bg-black dark:text-white"
aria-label="Deploy on Vercel"
href="https://vercel.com/templates/next.js/nextjs-commerce"
>
<span className="px-3"></span>
<hr className="h-full border-r border-neutral-200 dark:border-neutral-700" />
<span className="px-3">Deploy</span>
</a>
</div>
</div>
<div className="border-t border-neutral-200 py-6 text-sm dark:border-neutral-700">
<div className="mx-auto flex w-full max-w-7xl flex-col items-center gap-1 px-4 md:flex-row md:gap-0 md:px-4 min-[1320px]:px-0">
<p>
<div className="py-6 text-sm">
<div className="text-neutral-500 dark:text-neutral-400">
&copy; {copyrightDate} {copyrightName}
{copyrightName.length && !copyrightName.endsWith('.') ? '.' : ''} All rights reserved.
</p>
<hr className="mx-4 hidden h-4 w-[1px] border-l border-neutral-400 md:inline-block" />
<p>
<a href="https://github.com/vercel/commerce">View the source</a>
</p>
<p className="md:ml-auto">
<a href="https://vercel.com" className="text-black dark:text-white">
Created by Vercel
</a>
</p>
{copyrightName.length && !copyrightName.endsWith(".")
? "."
: ""}{" "}
All rights reserved.
</div>
</div>
</div>
</footer>

View File

@ -1,43 +1,32 @@
import CartModal from 'components/cart/modal';
import LogoSquare from 'components/logo-square';
import { getMenu } from 'lib/shopify';
import { Menu } from 'lib/shopify/types';
import Link from 'next/link';
import { Suspense } from 'react';
import MobileMenu from './mobile-menu';
import Search, { SearchSkeleton } from './search';
import Link from "next/link";
const { SITE_NAME } = process.env;
import LogoSquare from "@/components/logo-square";
import { getMenu } from "@/lib/store/menu";
import MobileMenu from "./mobile-menu";
import Search from "./search";
export async function Navbar() {
const menu = await getMenu('next-js-frontend-header-menu');
export default async function Navbar() {
const menu = await getMenu("navbar");
return (
<nav className="relative flex items-center justify-between p-4 lg:px-6">
<div className="block flex-none md:hidden">
<Suspense fallback={null}>
<MobileMenu menu={menu} />
</Suspense>
</div>
<div className="flex w-full items-center">
<div className="flex w-full md:w-1/3">
<Link
href="/"
prefetch={true}
className="mr-2 flex w-full items-center justify-center md:w-auto lg:mr-6"
>
<LogoSquare />
<div className="ml-2 flex-none text-sm font-medium uppercase md:hidden lg:block">
{SITE_NAME}
</div>
<span className="ml-2 flex-none text-sm font-medium uppercase">
Store
</span>
</Link>
{menu.length ? (
{menu?.items ? (
<ul className="hidden gap-6 text-sm md:flex md:items-center">
{menu.map((item: Menu) => (
{menu.items.map((item) => (
<li key={item.title}>
<Link
href={item.path}
prefetch={true}
className="text-neutral-500 underline-offset-4 hover:text-black hover:underline dark:text-neutral-400 dark:hover:text-neutral-300"
>
{item.title}
@ -48,14 +37,35 @@ export async function Navbar() {
) : null}
</div>
<div className="hidden justify-center md:flex md:w-1/3">
<Suspense fallback={<SearchSkeleton />}>
<Search />
</Suspense>
<Search />
</div>
<div className="flex justify-end md:w-1/3">
<CartModal />
<div className="flex items-center">
<button
aria-label="Open cart"
className="ml-4 flex h-11 w-11 items-center justify-center rounded-md border border-neutral-200 text-black transition-colors dark:border-neutral-700 dark:text-white"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className="h-4 w-4"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15.75 10.5V6a3.75 3.75 0 10-7.5 0v4.5m11.356-1.993l1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 01-1.12-1.243l1.264-12A1.125 1.125 0 015.513 7.5h12.974c.576 0 1.059.435 1.119 1.007zM8.625 10.5a.375.375 0 11-.75 0 .375.375 0 01.75 0zm7.5 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"
/>
</svg>
</button>
</div>
</div>
</div>
<div className="flex md:hidden">
<MobileMenu menu={menu} />
</div>
</nav>
);
}

View File

@ -1,15 +1,18 @@
'use client';
"use client";
import { Dialog, Transition } from '@headlessui/react';
import Link from 'next/link';
import { usePathname, useSearchParams } from 'next/navigation';
import { Fragment, Suspense, useEffect, useState } from 'react';
import { Dialog, Transition } from "@headlessui/react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { Fragment, useEffect, useState } from "react";
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline';
import { Menu } from 'lib/shopify/types';
import Search, { SearchSkeleton } from './search';
import { Menu } from "@/lib/store/menu";
import Search from "./search";
export default function MobileMenu({ menu }: { menu: Menu[] }) {
interface MobileMenuProps {
menu?: Menu;
}
export default function MobileMenu({ menu }: MobileMenuProps) {
const pathname = usePathname();
const searchParams = useSearchParams();
const [isOpen, setIsOpen] = useState(false);
@ -22,9 +25,9 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
setIsOpen(false);
}
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [isOpen]);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
useEffect(() => {
setIsOpen(false);
@ -35,10 +38,24 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
<button
onClick={openMobileMenu}
aria-label="Open mobile menu"
className="flex h-11 w-11 items-center justify-center rounded-md border border-neutral-200 text-black transition-colors md:hidden dark:border-neutral-700 dark:text-white"
className="flex h-11 w-11 items-center justify-center rounded-md border border-neutral-200 text-black transition-colors dark:border-neutral-700 dark:text-white md:hidden"
>
<Bars3Icon className="h-4" />
<svg
className="h-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4 6h16M4 12h16M4 18h16"
/>
</svg>
</button>
<Transition show={isOpen}>
<Dialog onClose={closeMobileMenu} className="relative z-50">
<Transition.Child
@ -68,22 +85,32 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
onClick={closeMobileMenu}
aria-label="Close mobile menu"
>
<XMarkIcon className="h-6" />
<svg
className="h-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
<div className="mb-4 w-full">
<Suspense fallback={<SearchSkeleton />}>
<Search />
</Suspense>
<Search />
</div>
{menu.length ? (
{menu?.items ? (
<ul className="flex w-full flex-col">
{menu.map((item: Menu) => (
{menu.items.map((item) => (
<li
className="py-2 text-xl text-black transition-colors hover:text-neutral-500 dark:text-white"
key={item.title}
className="py-2 text-xl text-black transition-colors hover:text-neutral-500 dark:text-white"
>
<Link href={item.path} prefetch={true} onClick={closeMobileMenu}>
<Link href={item.path} onClick={closeMobileMenu}>
{item.title}
</Link>
</li>

View File

@ -1,9 +1,14 @@
import Grid from 'components/grid';
import { GridTileImage } from 'components/grid/tile';
import { Product } from 'lib/shopify/types';
import Link from 'next/link';
import Grid from "components/grid";
import { GridTileImage } from "components/grid/tile";
import { Product } from "lib/store/types";
import { getImageUrl } from "lib/utils/image";
import Link from "next/link";
export default function ProductGridItems({ products }: { products: Product[] }) {
export default function ProductGridItems({
products,
}: {
products: Product[];
}) {
return (
<>
{products.map((product) => (
@ -18,9 +23,13 @@ export default function ProductGridItems({ products }: { products: Product[] })
label={{
title: product.title,
amount: product.priceRange.maxVariantPrice.amount,
currencyCode: product.priceRange.maxVariantPrice.currencyCode
currencyCode: product.priceRange.maxVariantPrice.currencyCode,
}}
src={product.featuredImage?.url}
src={
product.featuredImage
? getImageUrl(product.featuredImage.source)
: ""
}
fill
sizes="(min-width: 768px) 33vw, (min-width: 640px) 50vw, 100vw"
/>

View File

@ -1,37 +1,46 @@
import clsx from 'clsx';
import { Suspense } from 'react';
import { getCollections } from "@/lib/store/products";
import clsx from "clsx";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { getCollections } from 'lib/shopify';
import FilterList from './filter';
async function CollectionList() {
export default async function Collections() {
const collections = await getCollections();
return <FilterList list={collections} title="Collections" />;
}
const pathname = usePathname();
const skeleton = 'mb-3 h-4 w-5/6 animate-pulse rounded-sm';
const activeAndTitles = 'bg-neutral-800 dark:bg-neutral-300';
const items = 'bg-neutral-400 dark:bg-neutral-700';
export default function Collections() {
return (
<Suspense
fallback={
<div className="col-span-2 hidden h-[400px] w-full flex-none py-4 lg:block">
<div className={clsx(skeleton, activeAndTitles)} />
<div className={clsx(skeleton, activeAndTitles)} />
<div className={clsx(skeleton, items)} />
<div className={clsx(skeleton, items)} />
<div className={clsx(skeleton, items)} />
<div className={clsx(skeleton, items)} />
<div className={clsx(skeleton, items)} />
<div className={clsx(skeleton, items)} />
<div className={clsx(skeleton, items)} />
<div className={clsx(skeleton, items)} />
</div>
}
>
<CollectionList />
</Suspense>
<>
<nav className="mb-4 flex gap-2">
<Link
href="/search"
className={clsx(
"rounded-lg px-3 py-2 text-sm font-semibold hover:bg-neutral-100 hover:text-black dark:hover:bg-neutral-800 dark:hover:text-white",
{
"bg-neutral-100 text-black dark:bg-neutral-800 dark:text-white":
pathname === "/search",
"text-neutral-500 dark:text-neutral-400": pathname !== "/search",
}
)}
>
All
</Link>
{collections.map((collection) => (
<Link
key={collection.handle}
href={`/search/${collection.handle}`}
className={clsx(
"rounded-lg px-3 py-2 text-sm font-semibold hover:bg-neutral-100 hover:text-black dark:hover:bg-neutral-800 dark:hover:text-white",
{
"bg-neutral-100 text-black dark:bg-neutral-800 dark:text-white":
pathname === `/search/${collection.handle}`,
"text-neutral-500 dark:text-neutral-400":
pathname !== `/search/${collection.handle}`,
}
)}
>
{collection.title}
</Link>
))}
</nav>
</>
);
}

View File

@ -1,31 +1,33 @@
'use client';
"use client";
import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline';
import { GridTileImage } from 'components/grid/tile';
import { useProduct, useUpdateURL } from 'components/product/product-context';
import Image from 'next/image';
import { ArrowLeftIcon, ArrowRightIcon } from "@heroicons/react/24/outline";
import { GridTileImage } from "components/grid/tile";
import { useProduct } from "components/product/product-context";
import { Image } from "lib/store/types";
import { getImageUrl } from "lib/utils/image";
import NextImage from "next/image";
export function Gallery({ images }: { images: { src: string; altText: string }[] }) {
export function Gallery({ images }: { images: Image[] }) {
const { state, updateImage } = useProduct();
const updateURL = useUpdateURL();
const imageIndex = state.image ? parseInt(state.image) : 0;
const nextImageIndex = imageIndex + 1 < images.length ? imageIndex + 1 : 0;
const previousImageIndex = imageIndex === 0 ? images.length - 1 : imageIndex - 1;
const previousImageIndex =
imageIndex === 0 ? images.length - 1 : imageIndex - 1;
const buttonClassName =
'h-full px-6 transition-all ease-in-out hover:scale-110 hover:text-black dark:hover:text-white flex items-center justify-center';
"h-full px-6 transition-all ease-in-out hover:scale-110 hover:text-black dark:hover:text-white flex items-center justify-center";
return (
<form>
<div className="relative aspect-square h-full max-h-[550px] w-full overflow-hidden">
{images[imageIndex] && (
<Image
<NextImage
className="h-full w-full object-contain"
fill
sizes="(min-width: 1024px) 66vw, 100vw"
alt={images[imageIndex]?.altText as string}
src={images[imageIndex]?.src as string}
src={getImageUrl(images[imageIndex]?.source)}
priority={true}
/>
)}
@ -35,8 +37,7 @@ export function Gallery({ images }: { images: { src: string; altText: string }[]
<div className="mx-auto flex h-11 items-center rounded-full border border-white bg-neutral-50/80 text-neutral-500 backdrop-blur-sm dark:border-black dark:bg-neutral-900/80">
<button
formAction={() => {
const newState = updateImage(previousImageIndex.toString());
updateURL(newState);
updateImage(previousImageIndex.toString());
}}
aria-label="Previous product image"
className={buttonClassName}
@ -46,8 +47,7 @@ export function Gallery({ images }: { images: { src: string; altText: string }[]
<div className="mx-1 h-6 w-px bg-neutral-500"></div>
<button
formAction={() => {
const newState = updateImage(nextImageIndex.toString());
updateURL(newState);
updateImage(nextImageIndex.toString());
}}
aria-label="Next product image"
className={buttonClassName}
@ -65,18 +65,17 @@ export function Gallery({ images }: { images: { src: string; altText: string }[]
const isActive = index === imageIndex;
return (
<li key={image.src} className="h-20 w-20">
<li key={getImageUrl(image.source)} className="h-20 w-20">
<button
formAction={() => {
const newState = updateImage(index.toString());
updateURL(newState);
updateImage(index.toString());
}}
aria-label="Select product image"
className="h-full w-full"
>
<GridTileImage
alt={image.altText}
src={image.src}
src={getImageUrl(image.source)}
width={80}
height={80}
active={isActive}

View File

@ -0,0 +1,66 @@
import { GridTileImage } from "components/grid/tile";
import { getCollectionProducts } from "lib/store/products";
import type { Product } from "lib/store/types";
import { getImageUrl } from "lib/utils/image";
import Link from "next/link";
function MainProductCardItem({
item,
size,
priority,
}: {
item: Product;
size: "full" | "half";
priority?: boolean;
}) {
return (
<div
className={
size === "full"
? "md:col-span-4 md:row-span-2"
: "md:col-span-2 md:row-span-1"
}
>
<Link
className="relative block aspect-square h-full w-full"
href={`/product/${item.handle}`}
prefetch={true}
>
<GridTileImage
src={getImageUrl(item.featuredImage.source)}
fill
sizes={
size === "full"
? "(min-width: 768px) 66vw, 100vw"
: "(min-width: 768px) 33vw, 100vw"
}
priority={priority}
alt={item.title}
label={{
position: size === "full" ? "center" : "bottom",
title: item.title as string,
amount: item.priceRange.maxVariantPrice.amount,
currencyCode: item.priceRange.maxVariantPrice.currencyCode,
}}
/>
</Link>
</div>
);
}
export async function MainProductCard() {
// Collections that start with `hidden-*` are hidden from the search page.
const homepageItems = await getCollectionProducts({
collection: "hidden-homepage-featured-items",
});
if (!homepageItems[0]) return null;
const [firstProduct] = homepageItems;
return (
<section className="mx-auto grid max-w-(--breakpoint-2xl) gap-4 px-4 pb-4 md:grid-cols-6 md:grid-rows-2 lg:max-h-[calc(100vh-200px)]">
<MainProductCardItem size="full" item={firstProduct} priority={true} />
</section>
);
}

View File

@ -1,8 +1,8 @@
import { AddToCart } from 'components/cart/add-to-cart';
import Price from 'components/price';
import Prose from 'components/prose';
import { Product } from 'lib/shopify/types';
import { VariantSelector } from './variant-selector';
import { AddToCart } from "components/cart/add-to-cart";
import Price from "components/price";
import Prose from "components/prose";
import { Product } from "lib/store/types";
import { VariantSelector } from "./variant-selector";
export function ProductDescription({ product }: { product: Product }) {
return (
@ -16,7 +16,11 @@ export function ProductDescription({ product }: { product: Product }) {
/>
</div>
</div>
<VariantSelector options={product.options} variants={product.variants} />
<VariantSelector
options={product.options}
variants={product.variants}
selectedVariant={product.variants[0]!}
/>
{product.descriptionHtml ? (
<Prose
className="mb-6 text-sm leading-tight dark:text-white/[60%]"

View File

@ -1,93 +1,100 @@
'use client';
"use client";
import clsx from 'clsx';
import { useProduct, useUpdateURL } from 'components/product/product-context';
import { ProductOption, ProductVariant } from 'lib/shopify/types';
import { ProductOption, ProductVariant } from "@/lib/store/types";
import clsx from "clsx";
type Combination = {
id: string;
availableForSale: boolean;
[key: string]: string | boolean;
};
interface VariantSelectorProps {
options: ProductOption[];
variants: ProductVariant[];
selectedVariant: ProductVariant;
onVariantChange: (variant: ProductVariant) => void;
}
export function VariantSelector({
options,
variants
}: {
options: ProductOption[];
variants: ProductVariant[];
}) {
const { state, updateOption } = useProduct();
const updateURL = useUpdateURL();
const hasNoOptionsOrJustOneOption =
!options.length || (options.length === 1 && options[0]?.values.length === 1);
variants,
selectedVariant,
onVariantChange,
}: VariantSelectorProps) {
const getSelectedOptionValue = (optionName: string) => {
return selectedVariant.selectedOptions.find(
(option) => option.name === optionName
)?.value;
};
if (hasNoOptionsOrJustOneOption) {
return null;
}
const getVariantFromSelectedOptions = (
selectedOptions: Record<string, string>
) => {
return variants.find((variant) =>
variant.selectedOptions.every(
(option) => selectedOptions[option.name] === option.value
)
);
};
const combinations: Combination[] = variants.map((variant) => ({
id: variant.id,
availableForSale: variant.availableForSale,
...variant.selectedOptions.reduce(
(accumulator, option) => ({ ...accumulator, [option.name.toLowerCase()]: option.value }),
{}
)
}));
const handleOptionClick = (optionName: string, optionValue: string) => {
const selectedOptions = {
...Object.fromEntries(
selectedVariant.selectedOptions.map((option) => [
option.name,
option.value,
])
),
};
selectedOptions[optionName] = optionValue;
return options.map((option) => (
<form key={option.id}>
<dl className="mb-8">
<dt className="mb-4 text-sm uppercase tracking-wide">{option.name}</dt>
<dd className="flex flex-wrap gap-3">
{option.values.map((value) => {
const optionNameLowerCase = option.name.toLowerCase();
const newVariant = getVariantFromSelectedOptions(selectedOptions);
if (newVariant) {
onVariantChange(newVariant);
}
};
// Base option params on current selectedOptions so we can preserve any other param state.
const optionParams = { ...state, [optionNameLowerCase]: value };
return (
<div className="grid gap-4">
{options.map((option) => (
<div key={option.id} className="flex flex-col gap-2">
<p className="text-sm font-bold">{option.name}</p>
<div className="flex flex-wrap gap-2">
{option.values.map((value) => {
const isSelected = getSelectedOptionValue(option.name) === value;
const variant = getVariantFromSelectedOptions({
...Object.fromEntries(
selectedVariant.selectedOptions.map((opt) => [
opt.name,
opt.value,
])
),
[option.name]: value,
});
const isAvailable = variant?.availableForSale || false;
// Filter out invalid options and check if the option combination is available for sale.
const filtered = Object.entries(optionParams).filter(([key, value]) =>
options.find(
(option) => option.name.toLowerCase() === key && option.values.includes(value)
)
);
const isAvailableForSale = combinations.find((combination) =>
filtered.every(
([key, value]) => combination[key] === value && combination.availableForSale
)
);
// The option is active if it's in the selected options.
const isActive = state[optionNameLowerCase] === value;
return (
<button
formAction={() => {
const newState = updateOption(optionNameLowerCase, value);
updateURL(newState);
}}
key={value}
aria-disabled={!isAvailableForSale}
disabled={!isAvailableForSale}
title={`${option.name} ${value}${!isAvailableForSale ? ' (Out of Stock)' : ''}`}
className={clsx(
'flex min-w-[48px] items-center justify-center rounded-full border bg-neutral-100 px-2 py-1 text-sm dark:border-neutral-800 dark:bg-neutral-900',
{
'cursor-default ring-2 ring-blue-600': isActive,
'ring-1 ring-transparent transition duration-300 ease-in-out hover:ring-blue-600':
!isActive && isAvailableForSale,
'relative z-10 cursor-not-allowed overflow-hidden bg-neutral-100 text-neutral-500 ring-1 ring-neutral-300 before:absolute before:inset-x-0 before:-z-10 before:h-px before:-rotate-45 before:bg-neutral-300 before:transition-transform dark:bg-neutral-900 dark:text-neutral-400 dark:ring-neutral-700 dark:before:bg-neutral-700':
!isAvailableForSale
}
)}
>
{value}
</button>
);
})}
</dd>
</dl>
</form>
));
return (
<button
key={value}
onClick={() => handleOptionClick(option.name, value)}
className={clsx(
"flex min-w-[48px] items-center justify-center rounded-full border bg-neutral-100 px-2 py-1 text-sm dark:border-neutral-800 dark:bg-neutral-900",
{
"cursor-default ring-2 ring-blue-600": isSelected,
"ring-1 ring-transparent transition duration-100 hover:scale-110 hover:ring-blue-600":
!isSelected && isAvailable,
"relative z-10 cursor-not-allowed overflow-hidden bg-neutral-100 text-neutral-500 ring-0 hover:scale-100":
!isAvailable,
"cursor-pointer": isAvailable,
}
)}
disabled={!isAvailable}
>
{value}
{!isAvailable && (
<div className="absolute inset-0 -z-10 bg-neutral-300 dark:bg-neutral-700" />
)}
</button>
);
})}
</div>
</div>
))}
</div>
);
}

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

@ -0,0 +1,59 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"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",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"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 shadow-xs 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",
},
size: {
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",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@ -1,53 +0,0 @@
import productFragment from './product';
const cartFragment = /* GraphQL */ `
fragment cart on Cart {
id
checkoutUrl
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
}
product {
...product
}
}
}
}
}
}
totalQuantity
}
${productFragment}
`;
export default cartFragment;

View File

@ -1,10 +0,0 @@
const imageFragment = /* GraphQL */ `
fragment image on Image {
url
altText
width
height
}
`;
export default imageFragment;

View File

@ -1,64 +0,0 @@
import imageFragment from './image';
import seoFragment from './seo';
const productFragment = /* GraphQL */ `
fragment product on Product {
id
handle
availableForSale
title
description
descriptionHtml
options {
id
name
values
}
priceRange {
maxVariantPrice {
amount
currencyCode
}
minVariantPrice {
amount
currencyCode
}
}
variants(first: 250) {
edges {
node {
id
title
availableForSale
selectedOptions {
name
value
}
price {
amount
currencyCode
}
}
}
}
featuredImage {
...image
}
images(first: 20) {
edges {
node {
...image
}
}
}
seo {
...seo
}
tags
updatedAt
}
${imageFragment}
${seoFragment}
`;
export default productFragment;

View File

@ -1,8 +0,0 @@
const seoFragment = /* GraphQL */ `
fragment seo on SEO {
description
title
}
`;
export default seoFragment;

View File

@ -1,501 +0,0 @@
import {
HIDDEN_PRODUCT_TAG,
SHOPIFY_GRAPHQL_API_ENDPOINT,
TAGS
} from 'lib/constants';
import { isShopifyError } from 'lib/type-guards';
import { ensureStartsWith } from 'lib/utils';
import {
revalidateTag,
unstable_cacheTag as cacheTag,
unstable_cacheLife as cacheLife
} from 'next/cache';
import { cookies, headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import {
addToCartMutation,
createCartMutation,
editCartItemsMutation,
removeFromCartMutation
} from './mutations/cart';
import { getCartQuery } from './queries/cart';
import {
getCollectionProductsQuery,
getCollectionQuery,
getCollectionsQuery
} from './queries/collection';
import { getMenuQuery } from './queries/menu';
import { getPageQuery, getPagesQuery } from './queries/page';
import {
getProductQuery,
getProductRecommendationsQuery,
getProductsQuery
} from './queries/product';
import {
Cart,
Collection,
Connection,
Image,
Menu,
Page,
Product,
ShopifyAddToCartOperation,
ShopifyCart,
ShopifyCartOperation,
ShopifyCollection,
ShopifyCollectionOperation,
ShopifyCollectionProductsOperation,
ShopifyCollectionsOperation,
ShopifyCreateCartOperation,
ShopifyMenuOperation,
ShopifyPageOperation,
ShopifyPagesOperation,
ShopifyProduct,
ShopifyProductOperation,
ShopifyProductRecommendationsOperation,
ShopifyProductsOperation,
ShopifyRemoveFromCartOperation,
ShopifyUpdateCartOperation
} from './types';
const domain = process.env.SHOPIFY_STORE_DOMAIN
? ensureStartsWith(process.env.SHOPIFY_STORE_DOMAIN, 'https://')
: '';
const endpoint = `${domain}${SHOPIFY_GRAPHQL_API_ENDPOINT}`;
const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN!;
type ExtractVariables<T> = T extends { variables: object }
? T['variables']
: never;
export async function shopifyFetch<T>({
headers,
query,
variables
}: {
headers?: HeadersInit;
query: string;
variables?: ExtractVariables<T>;
}): Promise<{ status: number; body: T } | never> {
try {
const result = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': key,
...headers
},
body: JSON.stringify({
...(query && { query }),
...(variables && { variables })
})
});
const body = await result.json();
if (body.errors) {
throw body.errors[0];
}
return {
status: result.status,
body
};
} catch (e) {
if (isShopifyError(e)) {
throw {
cause: e.cause?.toString() || 'unknown',
status: e.status || 500,
message: e.message,
query
};
}
throw {
error: e,
query
};
}
}
const removeEdgesAndNodes = <T>(array: Connection<T>): T[] => {
return array.edges.map((edge) => edge?.node);
};
const reshapeCart = (cart: ShopifyCart): Cart => {
if (!cart.cost?.totalTaxAmount) {
cart.cost.totalTaxAmount = {
amount: '0.0',
currencyCode: cart.cost.totalAmount.currencyCode
};
}
return {
...cart,
lines: removeEdgesAndNodes(cart.lines)
};
};
const reshapeCollection = (
collection: ShopifyCollection
): Collection | undefined => {
if (!collection) {
return undefined;
}
return {
...collection,
path: `/search/${collection.handle}`
};
};
const reshapeCollections = (collections: ShopifyCollection[]) => {
const reshapedCollections = [];
for (const collection of collections) {
if (collection) {
const reshapedCollection = reshapeCollection(collection);
if (reshapedCollection) {
reshapedCollections.push(reshapedCollection);
}
}
}
return reshapedCollections;
};
const reshapeImages = (images: Connection<Image>, productTitle: string) => {
const flattened = removeEdgesAndNodes(images);
return flattened.map((image) => {
const filename = image.url.match(/.*\/(.*)\..*/)?.[1];
return {
...image,
altText: image.altText || `${productTitle} - ${filename}`
};
});
};
const reshapeProduct = (
product: ShopifyProduct,
filterHiddenProducts: boolean = true
) => {
if (
!product ||
(filterHiddenProducts && product.tags.includes(HIDDEN_PRODUCT_TAG))
) {
return undefined;
}
const { images, variants, ...rest } = product;
return {
...rest,
images: reshapeImages(images, product.title),
variants: removeEdgesAndNodes(variants)
};
};
const reshapeProducts = (products: ShopifyProduct[]) => {
const reshapedProducts = [];
for (const product of products) {
if (product) {
const reshapedProduct = reshapeProduct(product);
if (reshapedProduct) {
reshapedProducts.push(reshapedProduct);
}
}
}
return reshapedProducts;
};
export async function createCart(): Promise<Cart> {
const res = await shopifyFetch<ShopifyCreateCartOperation>({
query: createCartMutation
});
return reshapeCart(res.body.data.cartCreate.cart);
}
export async function addToCart(
lines: { merchandiseId: string; quantity: number }[]
): Promise<Cart> {
const cartId = (await cookies()).get('cartId')?.value!;
const res = await shopifyFetch<ShopifyAddToCartOperation>({
query: addToCartMutation,
variables: {
cartId,
lines
}
});
return reshapeCart(res.body.data.cartLinesAdd.cart);
}
export async function removeFromCart(lineIds: string[]): Promise<Cart> {
const cartId = (await cookies()).get('cartId')?.value!;
const res = await shopifyFetch<ShopifyRemoveFromCartOperation>({
query: removeFromCartMutation,
variables: {
cartId,
lineIds
}
});
return reshapeCart(res.body.data.cartLinesRemove.cart);
}
export async function updateCart(
lines: { id: string; merchandiseId: string; quantity: number }[]
): Promise<Cart> {
const cartId = (await cookies()).get('cartId')?.value!;
const res = await shopifyFetch<ShopifyUpdateCartOperation>({
query: editCartItemsMutation,
variables: {
cartId,
lines
}
});
return reshapeCart(res.body.data.cartLinesUpdate.cart);
}
export async function getCart(): Promise<Cart | undefined> {
const cartId = (await cookies()).get('cartId')?.value;
if (!cartId) {
return undefined;
}
const res = await shopifyFetch<ShopifyCartOperation>({
query: getCartQuery,
variables: { cartId }
});
// Old carts becomes `null` when you checkout.
if (!res.body.data.cart) {
return undefined;
}
return reshapeCart(res.body.data.cart);
}
export async function getCollection(
handle: string
): Promise<Collection | undefined> {
'use cache';
cacheTag(TAGS.collections);
cacheLife('days');
const res = await shopifyFetch<ShopifyCollectionOperation>({
query: getCollectionQuery,
variables: {
handle
}
});
return reshapeCollection(res.body.data.collection);
}
export async function getCollectionProducts({
collection,
reverse,
sortKey
}: {
collection: string;
reverse?: boolean;
sortKey?: string;
}): Promise<Product[]> {
'use cache';
cacheTag(TAGS.collections, TAGS.products);
cacheLife('days');
const res = await shopifyFetch<ShopifyCollectionProductsOperation>({
query: getCollectionProductsQuery,
variables: {
handle: collection,
reverse,
sortKey: sortKey === 'CREATED_AT' ? 'CREATED' : sortKey
}
});
if (!res.body.data.collection) {
console.log(`No collection found for \`${collection}\``);
return [];
}
return reshapeProducts(
removeEdgesAndNodes(res.body.data.collection.products)
);
}
export async function getCollections(): Promise<Collection[]> {
'use cache';
cacheTag(TAGS.collections);
cacheLife('days');
const res = await shopifyFetch<ShopifyCollectionsOperation>({
query: getCollectionsQuery
});
const shopifyCollections = removeEdgesAndNodes(res.body?.data?.collections);
const collections = [
{
handle: '',
title: 'All',
description: 'All products',
seo: {
title: 'All',
description: 'All products'
},
path: '/search',
updatedAt: new Date().toISOString()
},
// Filter out the `hidden` collections.
// Collections that start with `hidden-*` need to be hidden on the search page.
...reshapeCollections(shopifyCollections).filter(
(collection) => !collection.handle.startsWith('hidden')
)
];
return collections;
}
export async function getMenu(handle: string): Promise<Menu[]> {
'use cache';
cacheTag(TAGS.collections);
cacheLife('days');
const res = await shopifyFetch<ShopifyMenuOperation>({
query: getMenuQuery,
variables: {
handle
}
});
return (
res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({
title: item.title,
path: item.url
.replace(domain, '')
.replace('/collections', '/search')
.replace('/pages', '')
})) || []
);
}
export async function getPage(handle: string): Promise<Page> {
const res = await shopifyFetch<ShopifyPageOperation>({
query: getPageQuery,
variables: { handle }
});
return res.body.data.pageByHandle;
}
export async function getPages(): Promise<Page[]> {
const res = await shopifyFetch<ShopifyPagesOperation>({
query: getPagesQuery
});
return removeEdgesAndNodes(res.body.data.pages);
}
export async function getProduct(handle: string): Promise<Product | undefined> {
'use cache';
cacheTag(TAGS.products);
cacheLife('days');
const res = await shopifyFetch<ShopifyProductOperation>({
query: getProductQuery,
variables: {
handle
}
});
return reshapeProduct(res.body.data.product, false);
}
export async function getProductRecommendations(
productId: string
): Promise<Product[]> {
'use cache';
cacheTag(TAGS.products);
cacheLife('days');
const res = await shopifyFetch<ShopifyProductRecommendationsOperation>({
query: getProductRecommendationsQuery,
variables: {
productId
}
});
return reshapeProducts(res.body.data.productRecommendations);
}
export async function getProducts({
query,
reverse,
sortKey
}: {
query?: string;
reverse?: boolean;
sortKey?: string;
}): Promise<Product[]> {
'use cache';
cacheTag(TAGS.products);
cacheLife('days');
const res = await shopifyFetch<ShopifyProductsOperation>({
query: getProductsQuery,
variables: {
query,
reverse,
sortKey
}
});
return reshapeProducts(removeEdgesAndNodes(res.body.data.products));
}
// This is called from `app/api/revalidate.ts` so providers can control revalidation logic.
export async function revalidate(req: NextRequest): Promise<NextResponse> {
// We always need to respond with a 200 status code to Shopify,
// otherwise it will continue to retry the request.
const collectionWebhooks = [
'collections/create',
'collections/delete',
'collections/update'
];
const productWebhooks = [
'products/create',
'products/delete',
'products/update'
];
const topic = (await headers()).get('x-shopify-topic') || 'unknown';
const secret = req.nextUrl.searchParams.get('secret');
const isCollectionUpdate = collectionWebhooks.includes(topic);
const isProductUpdate = productWebhooks.includes(topic);
if (!secret || secret !== process.env.SHOPIFY_REVALIDATION_SECRET) {
console.error('Invalid revalidation secret.');
return NextResponse.json({ status: 401 });
}
if (!isCollectionUpdate && !isProductUpdate) {
// We don't need to revalidate anything for any other topics.
return NextResponse.json({ status: 200 });
}
if (isCollectionUpdate) {
revalidateTag(TAGS.collections);
}
if (isProductUpdate) {
revalidateTag(TAGS.products);
}
return NextResponse.json({ status: 200, revalidated: true, now: Date.now() });
}

View File

@ -1,45 +0,0 @@
import cartFragment from '../fragments/cart';
export const addToCartMutation = /* GraphQL */ `
mutation addToCart($cartId: ID!, $lines: [CartLineInput!]!) {
cartLinesAdd(cartId: $cartId, lines: $lines) {
cart {
...cart
}
}
}
${cartFragment}
`;
export const createCartMutation = /* GraphQL */ `
mutation createCart($lineItems: [CartLineInput!]) {
cartCreate(input: { lines: $lineItems }) {
cart {
...cart
}
}
}
${cartFragment}
`;
export const editCartItemsMutation = /* GraphQL */ `
mutation editCartItems($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
cartLinesUpdate(cartId: $cartId, lines: $lines) {
cart {
...cart
}
}
}
${cartFragment}
`;
export const removeFromCartMutation = /* GraphQL */ `
mutation removeFromCart($cartId: ID!, $lineIds: [ID!]!) {
cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
cart {
...cart
}
}
}
${cartFragment}
`;

View File

@ -1,10 +0,0 @@
import cartFragment from '../fragments/cart';
export const getCartQuery = /* GraphQL */ `
query getCart($cartId: ID!) {
cart(id: $cartId) {
...cart
}
}
${cartFragment}
`;

View File

@ -1,56 +0,0 @@
import productFragment from '../fragments/product';
import seoFragment from '../fragments/seo';
const collectionFragment = /* GraphQL */ `
fragment collection on Collection {
handle
title
description
seo {
...seo
}
updatedAt
}
${seoFragment}
`;
export const getCollectionQuery = /* GraphQL */ `
query getCollection($handle: String!) {
collection(handle: $handle) {
...collection
}
}
${collectionFragment}
`;
export const getCollectionsQuery = /* GraphQL */ `
query getCollections {
collections(first: 100, sortKey: TITLE) {
edges {
node {
...collection
}
}
}
}
${collectionFragment}
`;
export const getCollectionProductsQuery = /* GraphQL */ `
query getCollectionProducts(
$handle: String!
$sortKey: ProductCollectionSortKeys
$reverse: Boolean
) {
collection(handle: $handle) {
products(sortKey: $sortKey, reverse: $reverse, first: 100) {
edges {
node {
...product
}
}
}
}
}
${productFragment}
`;

View File

@ -1,10 +0,0 @@
export const getMenuQuery = /* GraphQL */ `
query getMenu($handle: String!) {
menu(handle: $handle) {
items {
title
url
}
}
}
`;

View File

@ -1,41 +0,0 @@
import seoFragment from '../fragments/seo';
const pageFragment = /* GraphQL */ `
fragment page on Page {
... on Page {
id
title
handle
body
bodySummary
seo {
...seo
}
createdAt
updatedAt
}
}
${seoFragment}
`;
export const getPageQuery = /* GraphQL */ `
query getPage($handle: String!) {
pageByHandle(handle: $handle) {
...page
}
}
${pageFragment}
`;
export const getPagesQuery = /* GraphQL */ `
query getPages {
pages(first: 100) {
edges {
node {
...page
}
}
}
}
${pageFragment}
`;

View File

@ -1,32 +0,0 @@
import productFragment from '../fragments/product';
export const getProductQuery = /* GraphQL */ `
query getProduct($handle: String!) {
product(handle: $handle) {
...product
}
}
${productFragment}
`;
export const getProductsQuery = /* GraphQL */ `
query getProducts($sortKey: ProductSortKeys, $reverse: Boolean, $query: String) {
products(sortKey: $sortKey, reverse: $reverse, query: $query, first: 100) {
edges {
node {
...product
}
}
}
}
${productFragment}
`;
export const getProductRecommendationsQuery = /* GraphQL */ `
query getProductRecommendations($productId: ID!) {
productRecommendations(productId: $productId) {
...product
}
}
${productFragment}
`;

View File

@ -1,272 +0,0 @@
export type Maybe<T> = T | null;
export type Connection<T> = {
edges: Array<Edge<T>>;
};
export type Edge<T> = {
node: T;
};
export type Cart = Omit<ShopifyCart, 'lines'> & {
lines: CartItem[];
};
export type CartProduct = {
id: string;
handle: string;
title: string;
featuredImage: Image;
};
export type CartItem = {
id: string | undefined;
quantity: number;
cost: {
totalAmount: Money;
};
merchandise: {
id: string;
title: string;
selectedOptions: {
name: string;
value: string;
}[];
product: CartProduct;
};
};
export type Collection = ShopifyCollection & {
path: string;
};
export type Image = {
url: string;
altText: string;
width: number;
height: number;
};
export type Menu = {
title: string;
path: string;
};
export type Money = {
amount: string;
currencyCode: string;
};
export type Page = {
id: string;
title: string;
handle: string;
body: string;
bodySummary: string;
seo?: SEO;
createdAt: string;
updatedAt: string;
};
export type Product = Omit<ShopifyProduct, 'variants' | 'images'> & {
variants: ProductVariant[];
images: Image[];
};
export type ProductOption = {
id: string;
name: string;
values: string[];
};
export type ProductVariant = {
id: string;
title: string;
availableForSale: boolean;
selectedOptions: {
name: string;
value: string;
}[];
price: Money;
};
export type SEO = {
title: string;
description: string;
};
export type ShopifyCart = {
id: string | undefined;
checkoutUrl: string;
cost: {
subtotalAmount: Money;
totalAmount: Money;
totalTaxAmount: Money;
};
lines: Connection<CartItem>;
totalQuantity: number;
};
export type ShopifyCollection = {
handle: string;
title: string;
description: string;
seo: SEO;
updatedAt: string;
};
export type ShopifyProduct = {
id: string;
handle: string;
availableForSale: boolean;
title: string;
description: string;
descriptionHtml: string;
options: ProductOption[];
priceRange: {
maxVariantPrice: Money;
minVariantPrice: Money;
};
variants: Connection<ProductVariant>;
featuredImage: Image;
images: Connection<Image>;
seo: SEO;
tags: string[];
updatedAt: string;
};
export type ShopifyCartOperation = {
data: {
cart: ShopifyCart;
};
variables: {
cartId: string;
};
};
export type ShopifyCreateCartOperation = {
data: { cartCreate: { cart: ShopifyCart } };
};
export type ShopifyAddToCartOperation = {
data: {
cartLinesAdd: {
cart: ShopifyCart;
};
};
variables: {
cartId: string;
lines: {
merchandiseId: string;
quantity: number;
}[];
};
};
export type ShopifyRemoveFromCartOperation = {
data: {
cartLinesRemove: {
cart: ShopifyCart;
};
};
variables: {
cartId: string;
lineIds: string[];
};
};
export type ShopifyUpdateCartOperation = {
data: {
cartLinesUpdate: {
cart: ShopifyCart;
};
};
variables: {
cartId: string;
lines: {
id: string;
merchandiseId: string;
quantity: number;
}[];
};
};
export type ShopifyCollectionOperation = {
data: {
collection: ShopifyCollection;
};
variables: {
handle: string;
};
};
export type ShopifyCollectionProductsOperation = {
data: {
collection: {
products: Connection<ShopifyProduct>;
};
};
variables: {
handle: string;
reverse?: boolean;
sortKey?: string;
};
};
export type ShopifyCollectionsOperation = {
data: {
collections: Connection<ShopifyCollection>;
};
};
export type ShopifyMenuOperation = {
data: {
menu?: {
items: {
title: string;
url: string;
}[];
};
};
variables: {
handle: string;
};
};
export type ShopifyPageOperation = {
data: { pageByHandle: Page };
variables: { handle: string };
};
export type ShopifyPagesOperation = {
data: {
pages: Connection<Page>;
};
};
export type ShopifyProductOperation = {
data: { product: ShopifyProduct };
variables: {
handle: string;
};
};
export type ShopifyProductRecommendationsOperation = {
data: {
productRecommendations: ShopifyProduct[];
};
variables: {
productId: string;
};
};
export type ShopifyProductsOperation = {
data: {
products: Connection<ShopifyProduct>;
};
variables: {
query?: string;
reverse?: boolean;
sortKey?: string;
};
};

34
lib/store/menu.ts Normal file
View File

@ -0,0 +1,34 @@
export interface MenuItem {
title: string;
path: string;
}
export interface Menu {
title: string;
items: MenuItem[];
}
const menus: Record<string, Menu> = {
footer: {
title: "Footer",
items: [
{ title: "About", path: "/about" },
{ title: "Shipping", path: "/shipping" },
{ title: "Terms of Service", path: "/terms" },
{ title: "Privacy Policy", path: "/privacy" },
],
},
navbar: {
title: "Navigation",
items: [
{ title: "All", path: "/search" },
{ title: "Electronics", path: "/search/electronics" },
{ title: "Books", path: "/search/books" },
{ title: "Clothing", path: "/search/clothing" },
],
},
};
export const getMenu = (handle: string): Promise<Menu | undefined> => {
return Promise.resolve(menus[handle]);
};

48
lib/store/pages.ts Normal file
View File

@ -0,0 +1,48 @@
export type Page = {
id: string;
handle: string;
title: string;
body: string;
bodySummary: string;
seo?: {
title: string;
description: string;
};
createdAt: string;
updatedAt: string;
};
const pages: Page[] = [
{
id: "1",
handle: "about",
title: "About Us",
body: "<h2>Welcome to Our Store</h2><p>We are dedicated to providing the best shopping experience for our customers.</p>",
bodySummary: "Learn about our store and our mission.",
seo: {
title: "About Us | Our Store",
description:
"Learn about our store and our mission to provide the best shopping experience.",
},
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
},
{
id: "2",
handle: "shipping",
title: "Shipping Information",
body: "<h2>Shipping Policy</h2><p>We offer worldwide shipping with competitive rates.</p>",
bodySummary: "Information about our shipping policies and rates.",
seo: {
title: "Shipping Information | Our Store",
description:
"Learn about our shipping policies and worldwide delivery options.",
},
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
},
];
export const getPage = (handle: string): Promise<Page | undefined> => {
return Promise.resolve(pages.find((page) => page.handle === handle));
};

163
lib/store/products.ts Normal file
View File

@ -0,0 +1,163 @@
import { Collection, Product } from "./types";
const products: Product[] = [
{
id: "1",
handle: "kinaskak-blokk",
availableForSale: true,
title: "Kínaskák stigatafla",
description: "50 blaða Kínaskák stigatafla sem rifblokk",
descriptionHtml: "<p>50 blaða Kínaskák stigatafla sem rifblokk</p>",
options: [
{
id: "default",
name: "Default",
values: ["Default"],
},
],
priceRange: {
maxVariantPrice: {
amount: "2499",
currencyCode: "ISK",
},
minVariantPrice: {
amount: "2499",
currencyCode: "ISK",
},
},
variants: [
{
id: "default",
title: "Kínaskák stigatafla",
availableForSale: true,
selectedOptions: [{ name: "Default", value: "Default" }],
price: {
amount: "2499",
currencyCode: "ISK",
},
},
],
featuredImage: {
source: {
type: "static",
path: "/images/products/kinaskak.png",
},
altText: "Kínaskák stigatafla",
},
images: [
{
source: {
type: "static",
path: "/images/products/kinaskak.png",
},
altText: "Kínaskák stigatafla",
},
{
source: {
type: "static",
path: "/images/products/kinaskak-back.jpg",
},
altText: "Kínaskák stigatafla - Bakhlið",
},
],
seo: {
title: "Kínaskák stigatafla",
description: "50 blaða Kínaskák stigatafla sem rifblokk",
},
tags: ["jacket", "leather", "classic"],
updatedAt: new Date().toISOString(),
},
];
const collections: Collection[] = [
{
handle: "jackets",
title: "Jackets",
description: "Our collection of premium jackets",
seo: {
title: "Jackets Collection",
description: "Explore our premium collection of jackets",
},
updatedAt: new Date().toISOString(),
},
];
export const getProduct = ({
handle,
}: {
handle: string;
}): Promise<Product | undefined> => {
return Promise.resolve(products.find((p) => p.handle === handle));
};
export const getProducts = ({
query,
reverse,
sortKey,
}: {
query?: string;
reverse?: boolean;
sortKey?: string;
} = {}): Promise<Product[]> => {
let filteredProducts = [...products];
if (query) {
const searchQuery = query.toLowerCase();
filteredProducts = filteredProducts.filter(
(product) =>
product.title.toLowerCase().includes(searchQuery) ||
product.description.toLowerCase().includes(searchQuery)
);
}
if (sortKey) {
filteredProducts.sort((a, b) => {
switch (sortKey) {
case "TITLE":
return reverse
? b.title.localeCompare(a.title)
: a.title.localeCompare(b.title);
case "PRICE":
return reverse
? parseFloat(b.priceRange.minVariantPrice.amount) -
parseFloat(a.priceRange.minVariantPrice.amount)
: parseFloat(a.priceRange.minVariantPrice.amount) -
parseFloat(b.priceRange.minVariantPrice.amount);
case "CREATED_AT":
return reverse
? new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
: new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime();
default:
return 0;
}
});
}
return Promise.resolve(filteredProducts);
};
export const getProductRecommendations = ({
productId,
}: {
productId: string;
}): Promise<Product[]> => {
// For now, just return other products excluding the current one
return Promise.resolve(products.filter((p) => p.id !== productId));
};
export const getCollectionProducts = ({
collection,
sortKey,
reverse,
}: {
collection: string;
sortKey?: string;
reverse?: boolean;
}): Promise<Product[]> => {
// For now, return all products since we don't have collection associations
return getProducts({ sortKey, reverse });
};
export const getCollections = (): Promise<Collection[]> => {
return Promise.resolve(collections);
};

78
lib/store/types.ts Normal file
View File

@ -0,0 +1,78 @@
export type Money = {
amount: string;
currencyCode: string;
};
export type ImageSource =
| {
url: string;
type: "remote";
}
| {
path: string;
type: "static";
};
export type Image = {
source: ImageSource;
altText: string;
width?: number;
height?: number;
};
export type ProductOption = {
id: string;
name: string;
values: string[];
};
export type ProductVariant = {
id: string;
title: string;
availableForSale: boolean;
selectedOptions: {
name: string;
value: string;
}[];
price: Money;
};
export type SEO = {
title: string;
description: string;
};
export type Product = {
id: string;
handle: string;
availableForSale: boolean;
title: string;
description: string;
descriptionHtml: string;
options: ProductOption[];
priceRange: {
maxVariantPrice: Money;
minVariantPrice: Money;
};
variants: ProductVariant[];
featuredImage: Image;
images: Image[];
seo: SEO;
tags: string[];
updatedAt: string;
};
export type Collection = {
handle: string;
title: string;
description: string;
seo: SEO;
updatedAt: string;
};
export type CartItem = {
merchandise: ProductVariant & {
product: Product;
};
quantity: number;
};

View File

@ -1,51 +1,49 @@
import { ReadonlyURLSearchParams } from 'next/navigation';
import { type ClassValue, clsx } from "clsx";
import { ReadonlyURLSearchParams } from "next/navigation";
import { twMerge } from "tailwind-merge";
export const baseUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL
? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
: 'http://localhost:3000';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export const createUrl = (
export const baseUrl = process.env.NEXT_PUBLIC_URL || "http://localhost:3000";
export function createUrl(
pathname: string,
params: URLSearchParams | ReadonlyURLSearchParams
) => {
) {
const paramsString = params.toString();
const queryString = `${paramsString.length ? '?' : ''}${paramsString}`;
const queryString = `${paramsString.length ? "?" : ""}${paramsString}`;
return `${pathname}${queryString}`;
};
}
export const ensureStartsWith = (stringToCheck: string, startsWith: string) =>
stringToCheck.startsWith(startsWith)
? stringToCheck
: `${startsWith}${stringToCheck}`;
export function ensureStartsWith(stringToCheck: string, startsWith: string) {
if (!stringToCheck || typeof stringToCheck !== "string") {
return stringToCheck;
}
if (stringToCheck.startsWith(startsWith)) {
return stringToCheck;
}
return `${startsWith}${stringToCheck}`;
}
export const validateEnvironmentVariables = () => {
const requiredEnvironmentVariables = [
'SHOPIFY_STORE_DOMAIN',
'SHOPIFY_STOREFRONT_ACCESS_TOKEN'
];
const missingEnvironmentVariables = [] as string[];
const requiredEnvironmentVariables: Record<string, string | undefined> = {
NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
};
requiredEnvironmentVariables.forEach((envVar) => {
if (!process.env[envVar]) {
missingEnvironmentVariables.push(envVar);
}
});
const missingEnvironmentVariables = Object.entries(
requiredEnvironmentVariables
)
.filter(([, value]) => !value)
.map(([key]) => key);
if (missingEnvironmentVariables.length) {
throw new Error(
`The following environment variables are missing. Your site will not work without them. Read more: https://vercel.com/docs/integrations/shopify#configure-environment-variables\n\n${missingEnvironmentVariables.join(
'\n'
)}\n`
);
}
if (
process.env.SHOPIFY_STORE_DOMAIN?.includes('[') ||
process.env.SHOPIFY_STORE_DOMAIN?.includes(']')
) {
throw new Error(
'Your `SHOPIFY_STORE_DOMAIN` environment variable includes brackets (ie. `[` and / or `]`). Your site will not work with them there. Please remove them.'
`Missing required environment variables: ${missingEnvironmentVariables.join(", ")}`
);
}
};

8
lib/utils/image.ts Normal file
View File

@ -0,0 +1,8 @@
import { ImageSource } from "../store/types";
export const getImageUrl = (source: ImageSource): string => {
if (source.type === "remote") {
return source.url;
}
return source.path;
};

View File

@ -11,12 +11,17 @@
"dependencies": {
"@headlessui/react": "^2.2.0",
"@heroicons/react": "^2.2.0",
"@radix-ui/react-slot": "^1.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"geist": "^1.3.1",
"lucide-react": "^0.482.0",
"next": "15.3.0-canary.9",
"react": "19.0.0",
"react-dom": "19.0.0",
"sonner": "^2.0.1",
"tailwind-merge": "^3.0.2",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.24.2"
},
"devDependencies": {

76
pnpm-lock.yaml generated
View File

@ -18,12 +18,21 @@ importers:
'@heroicons/react':
specifier: ^2.2.0
version: 2.2.0(react@19.0.0)
'@radix-ui/react-slot':
specifier: ^1.1.2
version: 1.1.2(@types/react@19.0.10)(react@19.0.0)
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
clsx:
specifier: ^2.1.1
version: 2.1.1
geist:
specifier: ^1.3.1
version: 1.3.1(next@15.3.0-canary.9(react-dom@19.0.0(react@19.0.0))(react@19.0.0))
lucide-react:
specifier: ^0.482.0
version: 0.482.0(react@19.0.0)
next:
specifier: 15.3.0-canary.9
version: 15.3.0-canary.9(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
@ -36,6 +45,12 @@ importers:
sonner:
specifier: ^2.0.1
version: 2.0.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
tailwind-merge:
specifier: ^3.0.2
version: 3.0.2
tailwindcss-animate:
specifier: ^1.0.7
version: 1.0.7(tailwindcss@4.0.8)
zod:
specifier: ^3.24.2
version: 3.24.2
@ -272,6 +287,24 @@ packages:
cpu: [x64]
os: [win32]
'@radix-ui/react-compose-refs@1.1.1':
resolution: {integrity: sha512-Y9VzoRDSJtgFMUCoiZBDVo084VQ5hfpXxVE+NgkdNsjiDBByiImMZKKhxMwCbdHvhlENG6a833CbFkOQvTricw==}
peerDependencies:
'@types/react': 19.0.10
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@radix-ui/react-slot@1.1.2':
resolution: {integrity: sha512-YAKxaiGsSQJ38VzKH86/BPRC4rh+b1Jpa+JneA5LRE7skmLPNAyeG8kPJj/oo4STLvlrs8vkf/iYyc3A5stYCQ==}
peerDependencies:
'@types/react': 19.0.10
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@react-aria/focus@3.19.1':
resolution: {integrity: sha512-bix9Bu1Ue7RPcYmjwcjhB14BMu2qzfJ3tMQLqDc9pweJA66nOw8DThy3IfVr8Z7j2PHktOLf9kcbiZpydKHqzg==}
peerDependencies:
@ -425,6 +458,9 @@ packages:
caniuse-lite@1.0.30001700:
resolution: {integrity: sha512-2S6XIXwaE7K7erT8dY+kLQcpa5ms63XlRkMkReXjle+kf6c5g38vyMl+Z5y8dSxOFDhcFe+nxnn261PLxBSQsQ==}
class-variance-authority@0.7.1:
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
client-only@0.0.1:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
@ -555,6 +591,11 @@ packages:
lodash.merge@4.6.2:
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
lucide-react@0.482.0:
resolution: {integrity: sha512-XM8PzHzSrg8ATmmO+fzf+JyYlVVdQnJjuyLDj2p4V2zEtcKeBNAqAoJIGFv1x2HSBa7kT8gpYUxwdQ0g7nypfw==}
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
nanoid@3.3.8:
resolution: {integrity: sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@ -710,6 +751,14 @@ packages:
tabbable@6.2.0:
resolution: {integrity: sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==}
tailwind-merge@3.0.2:
resolution: {integrity: sha512-l7z+OYZ7mu3DTqrL88RiKrKIqO3NcpEO8V/Od04bNpvk0kiIFndGEoqfuzvj4yuhRkHKjRkII2z+KS2HfPcSxw==}
tailwindcss-animate@1.0.7:
resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}
peerDependencies:
tailwindcss: '>=3.0.0 || insiders'
tailwindcss@4.0.8:
resolution: {integrity: sha512-Me7N5CKR+D2A1xdWA5t5+kjjT7bwnxZOE6/yDI/ixJdJokszsn2n++mdU5yJwrsTpqFX2B9ZNMBJDwcqk9C9lw==}
@ -882,6 +931,19 @@ snapshots:
'@next/swc-win32-x64-msvc@15.3.0-canary.9':
optional: true
'@radix-ui/react-compose-refs@1.1.1(@types/react@19.0.10)(react@19.0.0)':
dependencies:
react: 19.0.0
optionalDependencies:
'@types/react': 19.0.10
'@radix-ui/react-slot@1.1.2(@types/react@19.0.10)(react@19.0.0)':
dependencies:
'@radix-ui/react-compose-refs': 1.1.1(@types/react@19.0.10)(react@19.0.0)
react: 19.0.0
optionalDependencies:
'@types/react': 19.0.10
'@react-aria/focus@3.19.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0)':
dependencies:
'@react-aria/interactions': 3.23.0(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
@ -1031,6 +1093,10 @@ snapshots:
caniuse-lite@1.0.30001700: {}
class-variance-authority@0.7.1:
dependencies:
clsx: 2.1.1
client-only@0.0.1: {}
clsx@2.1.1: {}
@ -1131,6 +1197,10 @@ snapshots:
lodash.merge@4.6.2: {}
lucide-react@0.482.0(react@19.0.0):
dependencies:
react: 19.0.0
nanoid@3.3.8: {}
next@15.3.0-canary.9(react-dom@19.0.0(react@19.0.0))(react@19.0.0):
@ -1243,6 +1313,12 @@ snapshots:
tabbable@6.2.0: {}
tailwind-merge@3.0.2: {}
tailwindcss-animate@1.0.7(tailwindcss@4.0.8):
dependencies:
tailwindcss: 4.0.8
tailwindcss@4.0.8: {}
tapable@2.2.1: {}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB