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

View File

@ -1,6 +1,23 @@
import { revalidate } from 'lib/shopify'; import { revalidateTag } from "next/cache";
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from "next/server";
export const runtime = "edge";
export async function POST(req: NextRequest): Promise<NextResponse> { 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, description,
}); });
if (!result.success) { if (!result.success || !result.data?.redirect_url) {
toast.error("Failed to create checkout session"); toast.error("Failed to create checkout session");
return; return;
} }

View File

@ -1,8 +1,12 @@
@import 'tailwindcss'; @import 'tailwindcss';
@custom-variant dark (&:is(.dark *));
@plugin "@tailwindcss/container-queries"; @plugin "@tailwindcss/container-queries";
@plugin "@tailwindcss/typography"; @plugin "@tailwindcss/typography";
@plugin 'tailwindcss-animate';
@layer base { @layer base {
*, *,
::after, ::after,
@ -30,3 +34,119 @@ input,
button { 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; @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 { CartProvider } from "components/cart/cart-context";
import { Navbar } from 'components/layout/navbar'; import { Inter } from "next/font/google";
import { WelcomeToast } from 'components/welcome-toast'; import { ReactNode } from "react";
import { GeistSans } from 'geist/font/sans'; import "./globals.css";
import { getCart } from 'lib/shopify';
import { ReactNode } from 'react';
import { Toaster } from 'sonner';
import './globals.css';
import { baseUrl } from 'lib/utils';
const { SITE_NAME } = process.env; const inter = Inter({ subsets: ["latin"] });
export const metadata = {
metadataBase: new URL(baseUrl),
title: {
default: SITE_NAME!,
template: `%s | ${SITE_NAME}`
},
robots: {
follow: true,
index: true
}
};
export default async function RootLayout({ export default async function RootLayout({
children children,
}: { }: {
children: ReactNode; children: ReactNode;
}) { }) {
// Don't await the fetch, pass the Promise to the context provider
const cart = getCart();
return ( return (
<html lang="en" className={GeistSans.variable}> <html lang="en">
<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"> <body className={inter.className}>
<CartProvider cartPromise={cart}> <CartProvider>{children}</CartProvider>
<Navbar />
<main>
{children}
<Toaster closeButton />
<WelcomeToast />
</main>
</CartProvider>
</body> </body>
</html> </html>
); );

View File

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

View File

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

View File

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

View File

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

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 { getCollectionProducts } from "lib/store/products";
import Link from 'next/link'; import { getImageUrl } from "lib/utils/image";
import { GridTileImage } from './grid/tile'; import Link from "next/link";
import { GridTileImage } from "./grid/tile";
export async function Carousel() { export async function Carousel() {
// Collections that start with `hidden-*` are hidden from the search page. // 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; if (!products?.length) return null;
@ -19,15 +22,22 @@ export async function Carousel() {
key={`${product.handle}${i}`} 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" 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 <GridTileImage
alt={product.title} alt={product.title}
label={{ label={{
title: product.title, title: product.title,
amount: product.priceRange.maxVariantPrice.amount, 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 fill
sizes="(min-width: 1024px) 25vw, (min-width: 768px) 33vw, 50vw" 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 { TAGS } from "lib/constants";
import { import { revalidateTag } from "next/cache";
addToCart, import { RequestCookies } from "next/dist/server/web/spec-extension/cookies";
createCart, import { cookies } from "next/headers";
getCart,
removeFromCart,
updateCart
} from 'lib/shopify';
import { revalidateTag } from 'next/cache';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
export async function addItem( export interface CartItem {
prevState: any, id: string;
selectedVariantId: string | undefined 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) { if (!selectedVariantId) {
return 'Error adding item to cart'; return "Missing product variant ID";
} }
try { try {
await addToCart([{ merchandiseId: selectedVariantId, quantity: 1 }]); await addToCart(selectedVariantId);
revalidateTag(TAGS.cart); revalidateTag(TAGS.cart);
} catch (e) { } 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 { try {
const cart = await getCart(); const cart = await getCart();
if (!cart) { const lineItem = cart.find((line) => line.id === merchandiseId);
return 'Error fetching cart';
}
const lineItem = cart.lines.find( if (lineItem) {
(line) => line.merchandise.id === merchandiseId await removeFromCart(merchandiseId);
);
if (lineItem && lineItem.id) {
await removeFromCart([lineItem.id]);
revalidateTag(TAGS.cart); revalidateTag(TAGS.cart);
} else { } else {
return 'Item not found in cart'; return "Item not found in cart";
} }
} catch (e) { } catch (e) {
return 'Error removing item from cart'; return "Error removing item from cart";
} }
} }
export async function updateItemQuantity( export async function updateItemQuantity(
prevState: any, merchandiseId: string | undefined,
payload: { quantity: number
merchandiseId: string;
quantity: number;
}
) { ) {
const { merchandiseId, quantity } = payload; if (!merchandiseId) {
return "Missing product ID";
}
try { try {
const cart = await getCart(); const cart = await getCart();
if (!cart) { const lineItem = cart.find((line) => line.id === merchandiseId);
return 'Error fetching cart';
}
const lineItem = cart.lines.find( if (lineItem) {
(line) => line.merchandise.id === merchandiseId
);
if (lineItem && lineItem.id) {
if (quantity === 0) { if (quantity === 0) {
await removeFromCart([lineItem.id]); await removeFromCart(merchandiseId);
} else { } else {
await updateCart([ await updateCartItemQuantity(merchandiseId, quantity);
{
id: lineItem.id,
merchandiseId,
quantity
}
]);
} }
} else if (quantity > 0) { } else if (quantity > 0) {
// If the item doesn't exist in the cart and quantity > 0, add it await addToCart(merchandiseId);
await addToCart([{ merchandiseId, quantity }]);
} }
revalidateTag(TAGS.cart); revalidateTag(TAGS.cart);
} catch (e) { } 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 { PlusIcon } from "@heroicons/react/24/outline";
import clsx from 'clsx'; import clsx from "clsx";
import { addItem } from 'components/cart/actions'; import { addItem } from "components/cart/actions";
import { useProduct } from 'components/product/product-context'; import { useProduct } from "components/product/product-context";
import { Product, ProductVariant } from 'lib/shopify/types'; import { Product, ProductVariant } from "lib/store/types";
import { useActionState } from 'react'; import { useActionState } from "react";
import { useCart } from './cart-context'; import { useCart } from "./cart-context";
function SubmitButton({ function SubmitButton({
availableForSale, availableForSale,
selectedVariantId selectedVariantId,
}: { }: {
availableForSale: boolean; availableForSale: boolean;
selectedVariantId: string | undefined; selectedVariantId: string | undefined;
}) { }) {
const buttonClasses = const buttonClasses =
'relative flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white'; "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'; const disabledClasses = "cursor-not-allowed opacity-60 hover:opacity-60";
if (!availableForSale) { if (!availableForSale) {
return ( return (
@ -46,7 +46,7 @@ function SubmitButton({
<button <button
aria-label="Add to cart" aria-label="Add to cart"
className={clsx(buttonClasses, { className={clsx(buttonClasses, {
'hover:opacity-90': true "hover:opacity-90": true,
})} })}
> >
<div className="absolute left-0 ml-4"> <div className="absolute left-0 ml-4">
@ -61,7 +61,10 @@ export function AddToCart({ product }: { product: Product }) {
const { variants, availableForSale } = product; const { variants, availableForSale } = product;
const { addCartItem } = useCart(); const { addCartItem } = useCart();
const { state } = useProduct(); 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) => const variant = variants.find((variant: ProductVariant) =>
variant.selectedOptions.every( variant.selectedOptions.every(
@ -75,6 +78,13 @@ export function AddToCart({ product }: { product: Product }) {
(variant) => variant.id === selectedVariantId (variant) => variant.id === selectedVariantId
)!; )!;
console.log({
variant,
defaultVariantId,
selectedVariantId,
product,
});
return ( return (
<form <form
action={async () => { action={async () => {

View File

@ -1,204 +1,223 @@
'use client'; "use client";
import type { import { Product, ProductVariant } from "lib/store/types";
Cart, import { createContext, useContext, useState } from "react";
CartItem,
Product,
ProductVariant
} from 'lib/shopify/types';
import React, {
createContext,
use,
useContext,
useMemo,
useOptimistic
} from 'react';
type UpdateType = 'plus' | 'minus' | 'delete'; type CartItem = {
merchandise: ProductVariant & {
product: Product;
};
quantity: number;
};
type CartAction = type CartState = {
| { lines: CartItem[];
type: 'UPDATE_ITEM'; totalQuantity: number;
payload: { merchandiseId: string; updateType: UpdateType }; cost: {
} subtotalAmount: {
| { amount: string;
type: 'ADD_ITEM'; currencyCode: string;
payload: { variant: ProductVariant; product: Product };
}; };
totalAmount: {
amount: string;
currencyCode: string;
};
totalTaxAmount: {
amount: string;
currencyCode: string;
};
};
};
type CartContextType = { 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); const CartContext = createContext<CartContextType | undefined>(undefined);
function calculateItemCost(quantity: number, price: string): string { export function CartProvider({ children }: { children: React.ReactNode }) {
return (Number(price) * quantity).toString(); const [cart, setCart] = useState<CartState>({
}
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,
lines: [], lines: [],
totalQuantity: 0,
cost: { cost: {
subtotalAmount: { amount: '0', currencyCode: 'USD' }, subtotalAmount: {
totalAmount: { amount: '0', currencyCode: 'USD' }, amount: "0",
totalTaxAmount: { amount: '0', currencyCode: 'USD' } currencyCode: "USD",
} },
}; totalAmount: {
} amount: "0",
currencyCode: "USD",
},
totalTaxAmount: {
amount: "0",
currencyCode: "USD",
},
},
});
function cartReducer(state: Cart | undefined, action: CartAction): Cart { const addCartItem = (variant: ProductVariant, product: Product) => {
const currentCart = state || createEmptyCart(); setCart((prevCart) => {
const existingItem = prevCart.lines.find(
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(
(item) => item.merchandise.id === variant.id (item) => item.merchandise.id === variant.id
); );
const updatedItem = createOrUpdateCartItem(
existingItem, let newLines;
variant, if (existingItem) {
product 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 const subtotalAmount = newLines
? currentCart.lines.map((item) => .reduce(
item.merchandise.id === variant.id ? updatedItem : item (sum, item) =>
) sum + parseFloat(item.merchandise.price.amount) * item.quantity,
: [...currentCart.lines, updatedItem]; 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 { return {
...currentCart, lines: newLines,
...updateCartTotals(updatedLines), totalQuantity,
lines: updatedLines 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 ( return (
<CartContext.Provider value={{ cartPromise }}> <CartContext.Provider
value={{ cart, addCartItem, removeCartItem, updateCartItem }}
>
{children} {children}
</CartContext.Provider> </CartContext.Provider>
); );
@ -207,32 +226,7 @@ export function CartProvider({
export function useCart() { export function useCart() {
const context = useContext(CartContext); const context = useContext(CartContext);
if (context === undefined) { if (context === undefined) {
throw new Error('useCart must be used within a CartProvider'); throw new Error("useCart must be used within a CartProvider");
} }
return context;
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]
);
} }

View File

@ -1,38 +1,28 @@
'use client'; "use client";
import { XMarkIcon } from '@heroicons/react/24/outline'; import { XMarkIcon } from "@heroicons/react/24/outline";
import { removeItem } from 'components/cart/actions'; import clsx from "clsx";
import type { CartItem } from 'lib/shopify/types'; import { CartItem } from "lib/store/types";
import { useActionState } from 'react';
export function DeleteItemButton({ export function DeleteItemButton({
item, item,
optimisticUpdate onClick,
}: { }: {
item: CartItem; item: CartItem;
optimisticUpdate: any; onClick: () => void;
}) { }) {
const [message, formAction] = useActionState(removeItem, null);
const merchandiseId = item.merchandise.id;
const removeItemAction = formAction.bind(null, merchandiseId);
return ( return (
<form <button
action={async () => { aria-label="Remove cart item"
optimisticUpdate(merchandiseId, 'delete'); onClick={onClick}
removeItemAction(); 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 <XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
type="submit" </button>
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>
); );
} }

View File

@ -1,61 +1,38 @@
'use client'; "use client";
import { MinusIcon, PlusIcon } from '@heroicons/react/24/outline'; import { MinusIcon, PlusIcon } from "@heroicons/react/24/outline";
import clsx from 'clsx'; import clsx from "clsx";
import { updateItemQuantity } from 'components/cart/actions'; import { CartItem } from "lib/store/types";
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>
);
}
export function EditItemQuantityButton({ export function EditItemQuantityButton({
item, item,
type, type,
optimisticUpdate onClick,
}: { }: {
item: CartItem; item: CartItem;
type: 'plus' | 'minus'; type: "plus" | "minus";
optimisticUpdate: any; 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 ( return (
<form <button
action={async () => { aria-label={
optimisticUpdate(payload.merchandiseId, type); type === "plus" ? "Increase item quantity" : "Reduce item quantity"
updateItemQuantityAction(); }
}} 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} /> {type === "plus" ? (
<p aria-live="polite" className="sr-only" role="status"> <PlusIcon className="h-4 w-4" />
{message} ) : (
</p> <MinusIcon className="h-4 w-4" />
</form> )}
</button>
); );
} }

View File

@ -1,256 +1,310 @@
'use client'; "use client";
import clsx from 'clsx'; import { Dialog, Transition } from "@headlessui/react";
import { Dialog, Transition } from '@headlessui/react'; import { ShoppingCartIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ShoppingCartIcon, XMarkIcon } from '@heroicons/react/24/outline'; import Price from "components/price";
import LoadingDots from 'components/loading-dots'; import { DEFAULT_OPTION } from "lib/constants";
import Price from 'components/price'; import { createUrl } from "lib/utils";
import { DEFAULT_OPTION } from 'lib/constants'; import { getImageUrl } from "lib/utils/image";
import { createUrl } from 'lib/utils'; import Image from "next/image";
import Image from 'next/image'; import Link from "next/link";
import Link from 'next/link'; import { Fragment, useEffect, useRef } from "react";
import { Fragment, useEffect, useRef, useState } from 'react'; import { useCart } from "./cart-context";
import { useFormStatus } from 'react-dom'; import { EditItemQuantityButton } from "./edit-item-quantity-button";
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';
type MerchandiseSearchParams = { type MerchandiseSearchParams = {
[key: string]: string; [key: string]: string;
}; };
export default function CartModal() { export default function CartModal() {
const { cart, updateCartItem } = useCart(); const { cart, updateCartItem, removeCartItem } = useCart();
const [isOpen, setIsOpen] = useState(false); const quantityRef = useRef(cart.totalQuantity);
const quantityRef = useRef(cart?.totalQuantity); const openCart = () => {};
const openCart = () => setIsOpen(true); const closeCart = () => {};
const closeCart = () => setIsOpen(false);
useEffect(() => { useEffect(() => {
if (!cart) { // Open cart modal when quantity changes.
createCartAndSetCookie(); if (cart.totalQuantity !== quantityRef.current) {
// But only if it's not already open.
openCart();
} }
}, [cart]); quantityRef.current = cart.totalQuantity;
}, [cart.totalQuantity, openCart]);
useEffect(() => {
if (
cart?.totalQuantity &&
cart?.totalQuantity !== quantityRef.current &&
cart?.totalQuantity > 0
) {
if (!isOpen) {
setIsOpen(true);
}
quantityRef.current = cart?.totalQuantity;
}
}, [isOpen, cart?.totalQuantity, quantityRef]);
return ( return (
<> <>
<button aria-label="Open cart" onClick={openCart}> <button
<OpenCart quantity={cart?.totalQuantity} /> 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> </button>
<Transition show={isOpen}> <Transition.Root show={true} as={Fragment}>
<Dialog onClose={closeCart} className="relative z-50"> <Dialog onClose={closeCart} className="relative z-50">
<Transition.Child <Transition.Child
as={Fragment} as={Fragment}
enter="transition-all ease-in-out duration-300" enter="ease-in-out duration-500"
enterFrom="opacity-0 backdrop-blur-none" enterFrom="opacity-0"
enterTo="opacity-100 backdrop-blur-[.5px]" enterTo="opacity-100"
leave="transition-all ease-in-out duration-200" leave="ease-in-out duration-500"
leaveFrom="opacity-100 backdrop-blur-[.5px]" leaveFrom="opacity-100"
leaveTo="opacity-0 backdrop-blur-none" 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>
<Transition.Child
as={Fragment} <div className="fixed inset-0 overflow-hidden">
enter="transition-all ease-in-out duration-300" <div className="absolute inset-0 overflow-hidden">
enterFrom="translate-x-full" <div className="pointer-events-none fixed inset-y-0 right-0 flex max-w-full pl-10">
enterTo="translate-x-0" <Transition.Child
leave="transition-all ease-in-out duration-200" as={Fragment}
leaveFrom="translate-x-0" enter="transform transition ease-in-out duration-500"
leaveTo="translate-x-full" enterFrom="translate-x-full"
> enterTo="translate-x-0"
<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"> leave="transform transition ease-in-out duration-500"
<div className="flex items-center justify-between"> leaveFrom="translate-x-0"
<p className="text-lg font-semibold">My Cart</p> leaveTo="translate-x-full"
<button aria-label="Close cart" onClick={closeCart}> >
<CloseCart /> <Dialog.Panel className="pointer-events-auto w-screen max-w-md">
</button> <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> </div>
</div>
{!cart || cart.lines.length === 0 ? ( </div>
<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>
</Dialog> </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 { GridTileImage } from "components/grid/tile";
import { getCollectionProducts } from 'lib/shopify'; import { getCollectionProducts } from "lib/store/products";
import type { Product } from 'lib/shopify/types'; import type { Product } from "lib/store/types";
import Link from 'next/link'; import { getImageUrl } from "lib/utils/image";
import Link from "next/link";
function ThreeItemGridItem({ function ThreeItemGridItem({
item, item,
size, size,
priority priority,
}: { }: {
item: Product; item: Product;
size: 'full' | 'half'; size: "full" | "half";
priority?: boolean; priority?: boolean;
}) { }) {
return ( return (
<div <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 <Link
className="relative block aspect-square h-full w-full" className="relative block aspect-square h-full w-full"
@ -22,18 +27,20 @@ function ThreeItemGridItem({
prefetch={true} prefetch={true}
> >
<GridTileImage <GridTileImage
src={item.featuredImage.url} src={getImageUrl(item.featuredImage.source)}
fill fill
sizes={ 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} priority={priority}
alt={item.title} alt={item.title}
label={{ label={{
position: size === 'full' ? 'center' : 'bottom', position: size === "full" ? "center" : "bottom",
title: item.title as string, title: item.title as string,
amount: item.priceRange.maxVariantPrice.amount, amount: item.priceRange.maxVariantPrice.amount,
currencyCode: item.priceRange.maxVariantPrice.currencyCode currencyCode: item.priceRange.maxVariantPrice.currencyCode,
}} }}
/> />
</Link> </Link>
@ -44,7 +51,7 @@ function ThreeItemGridItem({
export async function ThreeItemGrid() { export async function ThreeItemGrid() {
// Collections that start with `hidden-*` are hidden from the search page. // Collections that start with `hidden-*` are hidden from the search page.
const homepageItems = await getCollectionProducts({ const homepageItems = await getCollectionProducts({
collection: 'hidden-homepage-featured-items' collection: "hidden-homepage-featured-items",
}); });
if (!homepageItems[0] || !homepageItems[1] || !homepageItems[2]) return null; if (!homepageItems[0] || !homepageItems[1] || !homepageItems[2]) return null;

View File

@ -1,46 +1,30 @@
'use client'; "use client";
import clsx from 'clsx'; import clsx from "clsx";
import { Menu } from 'lib/shopify/types'; import Link from "next/link";
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
export function FooterMenuItem({ item }: { item: Menu }) { import { Menu } from "@/lib/store/menu";
const pathname = usePathname();
const [active, setActive] = useState(pathname === item.path);
useEffect(() => { interface FooterMenuProps {
setActive(pathname === item.path); menu: Menu;
}, [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>
);
} }
export default function FooterMenu({ menu }: { menu: Menu[] }) { export default function FooterMenu({ menu }: FooterMenuProps) {
if (!menu.length) return null; if (!menu.items?.length) return null;
return ( return (
<nav> <nav className="grid grid-cols-2 gap-4 sm:grid-cols-3">
<ul> {menu.items.map((item) => (
{menu.map((item: Menu) => { <Link
return <FooterMenuItem key={item.title} item={item} />; key={item.title}
})} href={item.path}
</ul> 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> </nav>
); );
} }

View File

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

View File

@ -1,43 +1,32 @@
import CartModal from 'components/cart/modal'; import Link from "next/link";
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';
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() { export default async function Navbar() {
const menu = await getMenu('next-js-frontend-header-menu'); const menu = await getMenu("navbar");
return ( return (
<nav className="relative flex items-center justify-between p-4 lg:px-6"> <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 items-center">
<div className="flex w-full md:w-1/3"> <div className="flex w-full md:w-1/3">
<Link <Link
href="/" href="/"
prefetch={true}
className="mr-2 flex w-full items-center justify-center md:w-auto lg:mr-6" className="mr-2 flex w-full items-center justify-center md:w-auto lg:mr-6"
> >
<LogoSquare /> <LogoSquare />
<div className="ml-2 flex-none text-sm font-medium uppercase md:hidden lg:block"> <span className="ml-2 flex-none text-sm font-medium uppercase">
{SITE_NAME} Store
</div> </span>
</Link> </Link>
{menu.length ? ( {menu?.items ? (
<ul className="hidden gap-6 text-sm md:flex md:items-center"> <ul className="hidden gap-6 text-sm md:flex md:items-center">
{menu.map((item: Menu) => ( {menu.items.map((item) => (
<li key={item.title}> <li key={item.title}>
<Link <Link
href={item.path} 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" className="text-neutral-500 underline-offset-4 hover:text-black hover:underline dark:text-neutral-400 dark:hover:text-neutral-300"
> >
{item.title} {item.title}
@ -48,14 +37,35 @@ export async function Navbar() {
) : null} ) : null}
</div> </div>
<div className="hidden justify-center md:flex md:w-1/3"> <div className="hidden justify-center md:flex md:w-1/3">
<Suspense fallback={<SearchSkeleton />}> <Search />
<Search />
</Suspense>
</div> </div>
<div className="flex justify-end md:w-1/3"> <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> </div>
<div className="flex md:hidden">
<MobileMenu menu={menu} />
</div>
</nav> </nav>
); );
} }

View File

@ -1,15 +1,18 @@
'use client'; "use client";
import { Dialog, Transition } from '@headlessui/react'; import { Dialog, Transition } from "@headlessui/react";
import Link from 'next/link'; import Link from "next/link";
import { usePathname, useSearchParams } from 'next/navigation'; import { usePathname, useSearchParams } from "next/navigation";
import { Fragment, Suspense, useEffect, useState } from 'react'; import { Fragment, useEffect, useState } from "react";
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline'; import { Menu } from "@/lib/store/menu";
import { Menu } from 'lib/shopify/types'; import Search from "./search";
import Search, { SearchSkeleton } from './search';
export default function MobileMenu({ menu }: { menu: Menu[] }) { interface MobileMenuProps {
menu?: Menu;
}
export default function MobileMenu({ menu }: MobileMenuProps) {
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
@ -22,9 +25,9 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
setIsOpen(false); setIsOpen(false);
} }
}; };
window.addEventListener('resize', handleResize); window.addEventListener("resize", handleResize);
return () => window.removeEventListener('resize', handleResize); return () => window.removeEventListener("resize", handleResize);
}, [isOpen]); }, []);
useEffect(() => { useEffect(() => {
setIsOpen(false); setIsOpen(false);
@ -35,10 +38,24 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
<button <button
onClick={openMobileMenu} onClick={openMobileMenu}
aria-label="Open mobile menu" 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> </button>
<Transition show={isOpen}> <Transition show={isOpen}>
<Dialog onClose={closeMobileMenu} className="relative z-50"> <Dialog onClose={closeMobileMenu} className="relative z-50">
<Transition.Child <Transition.Child
@ -68,22 +85,32 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
onClick={closeMobileMenu} onClick={closeMobileMenu}
aria-label="Close mobile menu" 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> </button>
<div className="mb-4 w-full"> <div className="mb-4 w-full">
<Suspense fallback={<SearchSkeleton />}> <Search />
<Search />
</Suspense>
</div> </div>
{menu.length ? ( {menu?.items ? (
<ul className="flex w-full flex-col"> <ul className="flex w-full flex-col">
{menu.map((item: Menu) => ( {menu.items.map((item) => (
<li <li
className="py-2 text-xl text-black transition-colors hover:text-neutral-500 dark:text-white"
key={item.title} 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} {item.title}
</Link> </Link>
</li> </li>

View File

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

View File

@ -1,37 +1,46 @@
import clsx from 'clsx'; import { getCollections } from "@/lib/store/products";
import { Suspense } from 'react'; import clsx from "clsx";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { getCollections } from 'lib/shopify'; export default async function Collections() {
import FilterList from './filter';
async function CollectionList() {
const collections = await getCollections(); 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 ( return (
<Suspense <>
fallback={ <nav className="mb-4 flex gap-2">
<div className="col-span-2 hidden h-[400px] w-full flex-none py-4 lg:block"> <Link
<div className={clsx(skeleton, activeAndTitles)} /> href="/search"
<div className={clsx(skeleton, activeAndTitles)} /> className={clsx(
<div className={clsx(skeleton, items)} /> "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",
<div className={clsx(skeleton, items)} /> {
<div className={clsx(skeleton, items)} /> "bg-neutral-100 text-black dark:bg-neutral-800 dark:text-white":
<div className={clsx(skeleton, items)} /> pathname === "/search",
<div className={clsx(skeleton, items)} /> "text-neutral-500 dark:text-neutral-400": pathname !== "/search",
<div className={clsx(skeleton, items)} /> }
<div className={clsx(skeleton, items)} /> )}
<div className={clsx(skeleton, items)} /> >
</div> All
} </Link>
> {collections.map((collection) => (
<CollectionList /> <Link
</Suspense> 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 { ArrowLeftIcon, ArrowRightIcon } from "@heroicons/react/24/outline";
import { GridTileImage } from 'components/grid/tile'; import { GridTileImage } from "components/grid/tile";
import { useProduct, useUpdateURL } from 'components/product/product-context'; import { useProduct } from "components/product/product-context";
import Image from 'next/image'; 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 { state, updateImage } = useProduct();
const updateURL = useUpdateURL();
const imageIndex = state.image ? parseInt(state.image) : 0; const imageIndex = state.image ? parseInt(state.image) : 0;
const nextImageIndex = imageIndex + 1 < images.length ? imageIndex + 1 : 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 = 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 ( return (
<form> <form>
<div className="relative aspect-square h-full max-h-[550px] w-full overflow-hidden"> <div className="relative aspect-square h-full max-h-[550px] w-full overflow-hidden">
{images[imageIndex] && ( {images[imageIndex] && (
<Image <NextImage
className="h-full w-full object-contain" className="h-full w-full object-contain"
fill fill
sizes="(min-width: 1024px) 66vw, 100vw" sizes="(min-width: 1024px) 66vw, 100vw"
alt={images[imageIndex]?.altText as string} alt={images[imageIndex]?.altText as string}
src={images[imageIndex]?.src as string} src={getImageUrl(images[imageIndex]?.source)}
priority={true} 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"> <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 <button
formAction={() => { formAction={() => {
const newState = updateImage(previousImageIndex.toString()); updateImage(previousImageIndex.toString());
updateURL(newState);
}} }}
aria-label="Previous product image" aria-label="Previous product image"
className={buttonClassName} 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> <div className="mx-1 h-6 w-px bg-neutral-500"></div>
<button <button
formAction={() => { formAction={() => {
const newState = updateImage(nextImageIndex.toString()); updateImage(nextImageIndex.toString());
updateURL(newState);
}} }}
aria-label="Next product image" aria-label="Next product image"
className={buttonClassName} className={buttonClassName}
@ -65,18 +65,17 @@ export function Gallery({ images }: { images: { src: string; altText: string }[]
const isActive = index === imageIndex; const isActive = index === imageIndex;
return ( return (
<li key={image.src} className="h-20 w-20"> <li key={getImageUrl(image.source)} className="h-20 w-20">
<button <button
formAction={() => { formAction={() => {
const newState = updateImage(index.toString()); updateImage(index.toString());
updateURL(newState);
}} }}
aria-label="Select product image" aria-label="Select product image"
className="h-full w-full" className="h-full w-full"
> >
<GridTileImage <GridTileImage
alt={image.altText} alt={image.altText}
src={image.src} src={getImageUrl(image.source)}
width={80} width={80}
height={80} height={80}
active={isActive} 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 { AddToCart } from "components/cart/add-to-cart";
import Price from 'components/price'; import Price from "components/price";
import Prose from 'components/prose'; import Prose from "components/prose";
import { Product } from 'lib/shopify/types'; import { Product } from "lib/store/types";
import { VariantSelector } from './variant-selector'; import { VariantSelector } from "./variant-selector";
export function ProductDescription({ product }: { product: Product }) { export function ProductDescription({ product }: { product: Product }) {
return ( return (
@ -16,7 +16,11 @@ export function ProductDescription({ product }: { product: Product }) {
/> />
</div> </div>
</div> </div>
<VariantSelector options={product.options} variants={product.variants} /> <VariantSelector
options={product.options}
variants={product.variants}
selectedVariant={product.variants[0]!}
/>
{product.descriptionHtml ? ( {product.descriptionHtml ? (
<Prose <Prose
className="mb-6 text-sm leading-tight dark:text-white/[60%]" 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 { ProductOption, ProductVariant } from "@/lib/store/types";
import { useProduct, useUpdateURL } from 'components/product/product-context'; import clsx from "clsx";
import { ProductOption, ProductVariant } from 'lib/shopify/types';
type Combination = { interface VariantSelectorProps {
id: string; options: ProductOption[];
availableForSale: boolean; variants: ProductVariant[];
[key: string]: string | boolean; selectedVariant: ProductVariant;
}; onVariantChange: (variant: ProductVariant) => void;
}
export function VariantSelector({ export function VariantSelector({
options, options,
variants variants,
}: { selectedVariant,
options: ProductOption[]; onVariantChange,
variants: ProductVariant[]; }: VariantSelectorProps) {
}) { const getSelectedOptionValue = (optionName: string) => {
const { state, updateOption } = useProduct(); return selectedVariant.selectedOptions.find(
const updateURL = useUpdateURL(); (option) => option.name === optionName
const hasNoOptionsOrJustOneOption = )?.value;
!options.length || (options.length === 1 && options[0]?.values.length === 1); };
if (hasNoOptionsOrJustOneOption) { const getVariantFromSelectedOptions = (
return null; selectedOptions: Record<string, string>
} ) => {
return variants.find((variant) =>
variant.selectedOptions.every(
(option) => selectedOptions[option.name] === option.value
)
);
};
const combinations: Combination[] = variants.map((variant) => ({ const handleOptionClick = (optionName: string, optionValue: string) => {
id: variant.id, const selectedOptions = {
availableForSale: variant.availableForSale, ...Object.fromEntries(
...variant.selectedOptions.reduce( selectedVariant.selectedOptions.map((option) => [
(accumulator, option) => ({ ...accumulator, [option.name.toLowerCase()]: option.value }), option.name,
{} option.value,
) ])
})); ),
};
selectedOptions[optionName] = optionValue;
return options.map((option) => ( const newVariant = getVariantFromSelectedOptions(selectedOptions);
<form key={option.id}> if (newVariant) {
<dl className="mb-8"> onVariantChange(newVariant);
<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();
// Base option params on current selectedOptions so we can preserve any other param state. return (
const optionParams = { ...state, [optionNameLowerCase]: value }; <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. return (
const filtered = Object.entries(optionParams).filter(([key, value]) => <button
options.find( key={value}
(option) => option.name.toLowerCase() === key && option.values.includes(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",
const isAvailableForSale = combinations.find((combination) => {
filtered.every( "cursor-default ring-2 ring-blue-600": isSelected,
([key, value]) => combination[key] === value && combination.availableForSale "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,
// The option is active if it's in the selected options. "cursor-pointer": isAvailable,
const isActive = state[optionNameLowerCase] === value; }
)}
return ( disabled={!isAvailable}
<button >
formAction={() => { {value}
const newState = updateOption(optionNameLowerCase, value); {!isAvailable && (
updateURL(newState); <div className="absolute inset-0 -z-10 bg-neutral-300 dark:bg-neutral-700" />
}} )}
key={value} </button>
aria-disabled={!isAvailableForSale} );
disabled={!isAvailableForSale} })}
title={`${option.name} ${value}${!isAvailableForSale ? ' (Out of Stock)' : ''}`} </div>
className={clsx( </div>
'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', ))}
{ </div>
'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>
));
} }

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 export function cn(...inputs: ClassValue[]) {
? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` return twMerge(clsx(inputs));
: 'http://localhost:3000'; }
export const createUrl = ( export const baseUrl = process.env.NEXT_PUBLIC_URL || "http://localhost:3000";
export function createUrl(
pathname: string, pathname: string,
params: URLSearchParams | ReadonlyURLSearchParams params: URLSearchParams | ReadonlyURLSearchParams
) => { ) {
const paramsString = params.toString(); const paramsString = params.toString();
const queryString = `${paramsString.length ? '?' : ''}${paramsString}`; const queryString = `${paramsString.length ? "?" : ""}${paramsString}`;
return `${pathname}${queryString}`; return `${pathname}${queryString}`;
}; }
export const ensureStartsWith = (stringToCheck: string, startsWith: string) => export function ensureStartsWith(stringToCheck: string, startsWith: string) {
stringToCheck.startsWith(startsWith) if (!stringToCheck || typeof stringToCheck !== "string") {
? stringToCheck return stringToCheck;
: `${startsWith}${stringToCheck}`; }
if (stringToCheck.startsWith(startsWith)) {
return stringToCheck;
}
return `${startsWith}${stringToCheck}`;
}
export const validateEnvironmentVariables = () => { export const validateEnvironmentVariables = () => {
const requiredEnvironmentVariables = [ const requiredEnvironmentVariables: Record<string, string | undefined> = {
'SHOPIFY_STORE_DOMAIN', NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
'SHOPIFY_STOREFRONT_ACCESS_TOKEN' };
];
const missingEnvironmentVariables = [] as string[];
requiredEnvironmentVariables.forEach((envVar) => { const missingEnvironmentVariables = Object.entries(
if (!process.env[envVar]) { requiredEnvironmentVariables
missingEnvironmentVariables.push(envVar); )
} .filter(([, value]) => !value)
}); .map(([key]) => key);
if (missingEnvironmentVariables.length) { if (missingEnvironmentVariables.length) {
throw new Error( 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( `Missing required environment variables: ${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.'
); );
} }
}; };

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": { "dependencies": {
"@headlessui/react": "^2.2.0", "@headlessui/react": "^2.2.0",
"@heroicons/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", "clsx": "^2.1.1",
"geist": "^1.3.1", "geist": "^1.3.1",
"lucide-react": "^0.482.0",
"next": "15.3.0-canary.9", "next": "15.3.0-canary.9",
"react": "19.0.0", "react": "19.0.0",
"react-dom": "19.0.0", "react-dom": "19.0.0",
"sonner": "^2.0.1", "sonner": "^2.0.1",
"tailwind-merge": "^3.0.2",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.24.2" "zod": "^3.24.2"
}, },
"devDependencies": { "devDependencies": {

76
pnpm-lock.yaml generated
View File

@ -18,12 +18,21 @@ importers:
'@heroicons/react': '@heroicons/react':
specifier: ^2.2.0 specifier: ^2.2.0
version: 2.2.0(react@19.0.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: clsx:
specifier: ^2.1.1 specifier: ^2.1.1
version: 2.1.1 version: 2.1.1
geist: geist:
specifier: ^1.3.1 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)) 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: next:
specifier: 15.3.0-canary.9 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) 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: sonner:
specifier: ^2.0.1 specifier: ^2.0.1
version: 2.0.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0) 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: zod:
specifier: ^3.24.2 specifier: ^3.24.2
version: 3.24.2 version: 3.24.2
@ -272,6 +287,24 @@ packages:
cpu: [x64] cpu: [x64]
os: [win32] 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': '@react-aria/focus@3.19.1':
resolution: {integrity: sha512-bix9Bu1Ue7RPcYmjwcjhB14BMu2qzfJ3tMQLqDc9pweJA66nOw8DThy3IfVr8Z7j2PHktOLf9kcbiZpydKHqzg==} resolution: {integrity: sha512-bix9Bu1Ue7RPcYmjwcjhB14BMu2qzfJ3tMQLqDc9pweJA66nOw8DThy3IfVr8Z7j2PHktOLf9kcbiZpydKHqzg==}
peerDependencies: peerDependencies:
@ -425,6 +458,9 @@ packages:
caniuse-lite@1.0.30001700: caniuse-lite@1.0.30001700:
resolution: {integrity: sha512-2S6XIXwaE7K7erT8dY+kLQcpa5ms63XlRkMkReXjle+kf6c5g38vyMl+Z5y8dSxOFDhcFe+nxnn261PLxBSQsQ==} 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: client-only@0.0.1:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
@ -555,6 +591,11 @@ packages:
lodash.merge@4.6.2: lodash.merge@4.6.2:
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} 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: nanoid@3.3.8:
resolution: {integrity: sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==} resolution: {integrity: sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@ -710,6 +751,14 @@ packages:
tabbable@6.2.0: tabbable@6.2.0:
resolution: {integrity: sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==} 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: tailwindcss@4.0.8:
resolution: {integrity: sha512-Me7N5CKR+D2A1xdWA5t5+kjjT7bwnxZOE6/yDI/ixJdJokszsn2n++mdU5yJwrsTpqFX2B9ZNMBJDwcqk9C9lw==} resolution: {integrity: sha512-Me7N5CKR+D2A1xdWA5t5+kjjT7bwnxZOE6/yDI/ixJdJokszsn2n++mdU5yJwrsTpqFX2B9ZNMBJDwcqk9C9lw==}
@ -882,6 +931,19 @@ snapshots:
'@next/swc-win32-x64-msvc@15.3.0-canary.9': '@next/swc-win32-x64-msvc@15.3.0-canary.9':
optional: true 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)': '@react-aria/focus@3.19.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0)':
dependencies: dependencies:
'@react-aria/interactions': 3.23.0(react-dom@19.0.0(react@19.0.0))(react@19.0.0) '@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: {} caniuse-lite@1.0.30001700: {}
class-variance-authority@0.7.1:
dependencies:
clsx: 2.1.1
client-only@0.0.1: {} client-only@0.0.1: {}
clsx@2.1.1: {} clsx@2.1.1: {}
@ -1131,6 +1197,10 @@ snapshots:
lodash.merge@4.6.2: {} lodash.merge@4.6.2: {}
lucide-react@0.482.0(react@19.0.0):
dependencies:
react: 19.0.0
nanoid@3.3.8: {} nanoid@3.3.8: {}
next@15.3.0-canary.9(react-dom@19.0.0(react@19.0.0))(react@19.0.0): 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: {} 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: {} tailwindcss@4.0.8: {}
tapable@2.2.1: {} 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