mirror of
https://github.com/vercel/commerce.git
synced 2025-05-18 23:46:58 +00:00
Merge remote-tracking branch 'upstream/ppr' into sol/2023-11-12-merge-test
This commit is contained in:
commit
12bcdd8a3c
6
.github/workflows/test.yml
vendored
6
.github/workflows/test.yml
vendored
@ -5,11 +5,11 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Cancel running workflows
|
- name: Cancel running workflows
|
||||||
uses: styfle/cancel-workflow-action@0.11.0
|
uses: styfle/cancel-workflow-action@0.12.0
|
||||||
with:
|
with:
|
||||||
access_token: ${{ github.token }}
|
access_token: ${{ github.token }}
|
||||||
- name: Checkout repo
|
- name: Checkout repo
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
- name: Set node version
|
- name: Set node version
|
||||||
uses: actions/setup-node@v3
|
uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
@ -27,6 +27,6 @@ jobs:
|
|||||||
key: node-modules-cache-${{ hashFiles('**/pnpm-lock.yaml') }}
|
key: node-modules-cache-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
if: steps.node-modules-cache.outputs.cache-hit != 'true'
|
if: steps.node-modules-cache.outputs.cache-hit != 'true'
|
||||||
run: pnpm install
|
run: pnpm install --no-frozen-lockfile
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pnpm test
|
run: pnpm test
|
||||||
|
211
README.md
211
README.md
@ -23,13 +23,26 @@ A Next.js 13 and App Router-ready ecommerce template featuring:
|
|||||||
|
|
||||||
Vercel will only be actively maintaining a Shopify version [as outlined in our vision and strategy for Next.js Commerce](https://github.com/vercel/commerce/pull/966).
|
Vercel will only be actively maintaining a Shopify version [as outlined in our vision and strategy for Next.js Commerce](https://github.com/vercel/commerce/pull/966).
|
||||||
|
|
||||||
Vercel is more than happy to partner and work with any commerce provider to help them get a similar template up and running and listed below. Alternative providers should be able to fork this repository and swap out the `lib/shopify` file with their own implementation while leaving the rest of the template mostly unchanged.
|
Vercel is happy to partner and work with any commerce provider to help them get a similar template up and running and listed below. Alternative providers should be able to fork this repository and swap out the `lib/shopify` file with their own implementation while leaving the rest of the template mostly unchanged.
|
||||||
|
|
||||||
- Shopify (this repository)
|
- Shopify (this repository)
|
||||||
- [BigCommerce](https://github.com/bigcommerce/nextjs-commerce) ([Demo](https://next-commerce-v2.vercel.app/))
|
- [BigCommerce](https://github.com/bigcommerce/nextjs-commerce) ([Demo](https://next-commerce-v2.vercel.app/))
|
||||||
- [Medusa](https://github.com/medusajs/vercel-commerce) ([Demo](https://medusa-nextjs-commerce.vercel.app/))
|
- [Medusa](https://github.com/medusajs/vercel-commerce) ([Demo](https://medusa-nextjs-commerce.vercel.app/))
|
||||||
- [Saleor](https://github.com/saleor/nextjs-commerce) ([Demo](https://saleor-commerce.vercel.app/))
|
- [Saleor](https://github.com/saleor/nextjs-commerce) ([Demo](https://saleor-commerce.vercel.app/))
|
||||||
|
- [Shopware](https://github.com/shopwareLabs/vercel-commerce) ([Demo](https://shopware-vercel-commerce-react.vercel.app/))
|
||||||
- [Swell](https://github.com/swellstores/verswell-commerce) ([Demo](https://verswell-commerce.vercel.app/))
|
- [Swell](https://github.com/swellstores/verswell-commerce) ([Demo](https://verswell-commerce.vercel.app/))
|
||||||
|
- [Umbraco](https://github.com/umbraco/Umbraco.VercelCommerce.Demo) ([Demo](https://vercel-commerce-demo.umbraco.com/))
|
||||||
|
- [Wix](https://github.com/wix/nextjs-commerce) ([Demo](https://wix-nextjs-commerce.vercel.app/))
|
||||||
|
|
||||||
|
> Note: Providers, if you are looking to use similar products for your demo, you can [download these assets](https://drive.google.com/file/d/1q_bKerjrwZgHwCw0ovfUMW6He9VtepO_/view?usp=sharing).
|
||||||
|
|
||||||
|
## Integrations
|
||||||
|
|
||||||
|
Integrations enable upgraded or additional functionality for Next.js Commerce
|
||||||
|
|
||||||
|
- [Orama](https://github.com/oramasearch/nextjs-commerce) ([Demo](https://vercel-commerce.oramasearch.com/))
|
||||||
|
- Upgrades search to include typeahead with dynamic re-rendering, vector-based similarity search, and JS-based configuration.
|
||||||
|
- Search runs entirely in the browser for smaller catalogs or on a CDN for larger.
|
||||||
|
|
||||||
## Running locally
|
## Running locally
|
||||||
|
|
||||||
@ -55,199 +68,9 @@ Your app should now be running on [localhost:3000](http://localhost:3000/).
|
|||||||
1. Select the `Vercel Solutions` scope.
|
1. Select the `Vercel Solutions` scope.
|
||||||
1. Connect to the existing `commerce-shopify` project.
|
1. Connect to the existing `commerce-shopify` project.
|
||||||
1. Run `vc env pull` to get environment variables.
|
1. Run `vc env pull` to get environment variables.
|
||||||
1. Run `pmpm dev` to ensure everything is working correctly.
|
1. Run `pnpm dev` to ensure everything is working correctly.
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
## How to configure your Shopify store for Next.js Commerce
|
## Vercel, Next.js Commerce, and Shopify Integration Guide
|
||||||
|
|
||||||
Next.js Commerce requires a [paid Shopify plan](https://www.shopify.com/pricing).
|
You can use this comprehensive [integration guide](http://vercel.com/docs/integrations/shopify) with step-by-step instructions on how to configure Shopify as a headless CMS using Next.js Commerce as your headless Shopify storefront on Vercel.
|
||||||
|
|
||||||
> Note: Next.js Commerce will not work with a Shopify Starter plan as it does not allow installation of custom themes, which is required to run as a headless storefront.
|
|
||||||
|
|
||||||
### Add Shopify domain to an environment variable
|
|
||||||
|
|
||||||
Create a `SHOPIFY_STORE_DOMAIN` environment variable and use your Shopify domain as the the value (ie. `[your-shopify-store-subdomain].myshopify.com`).
|
|
||||||
|
|
||||||
> Note: Do not include the `https://`.
|
|
||||||
|
|
||||||
### Accessing the Shopify Storefront API
|
|
||||||
|
|
||||||
Next.js Commerce utilizes [Shopify's Storefront API](https://shopify.dev/docs/api/storefront) to create unique customer experiences. The API offers a full range of commerce options making it possible for customers to control products, collections, menus, pages, cart, checkout, and more.
|
|
||||||
|
|
||||||
In order to use the Shopify's Storefront API, you need to install the [Headless app](https://apps.shopify.com/headless) in your Shopify store.
|
|
||||||
|
|
||||||
Once installed, you'll need to create a `SHOPIFY_STOREFRONT_ACCESS_TOKEN` environment variable and use the public access token as the value.
|
|
||||||
|
|
||||||
> Note: Shopify does offer a Node.js Storefront API SDK. We use the Storefront API via GraphQL directly instead of the Node.js SDK so we have more control over fetching and caching.
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Expand to view detailed walkthrough</summary>
|
|
||||||
|
|
||||||
1. Navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/settings/apps`.
|
|
||||||
1. Click the green `Shopify App Store` button. 
|
|
||||||
1. Search for `Headless` and click on the `Headless` app. 
|
|
||||||
1. Click the black `Add app` button. 
|
|
||||||
1. Click the green `Add sales channel` button. 
|
|
||||||
1. Click the green `Create storefront` button. 
|
|
||||||
1. Copy and paste the public access token and assign it to a `SHOPIFY_STOREFRONT_ACCESS_TOKEN` environment variable. 
|
|
||||||
1. If you ever need to reference the public access token again, you can navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/headless_storefronts`.
|
|
||||||
</details>
|
|
||||||
|
|
||||||
### Install a headless theme
|
|
||||||
|
|
||||||
When using a headless Shopify setup, you normally don't want customers to access any of the theme pages except for checkout. However, you can't totally disable the theme and a lot of links will still point to the theme (e.g. links in emails, order details, plugins, checkout, etc.).
|
|
||||||
|
|
||||||
To enable a seamless flow between your headless site and Shopify, you can install the [Shopify Headless Theme](https://github.com/instantcommerce/shopify-headless-theme).
|
|
||||||
|
|
||||||
Follow the installation instructions and configure the theme with your headless site's values.
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Expand to view detailed walkthrough</summary>
|
|
||||||
|
|
||||||
1. Download [Shopify Headless Theme](https://github.com/instantcommerce/shopify-headless-theme). 
|
|
||||||
1. Navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/themes`.
|
|
||||||
1. Click `Add theme`, then `Upload zip file`. 
|
|
||||||
1. Select the downloaded zip file from above, and click the green `Upload file` button. 
|
|
||||||
1. Click `Customize`. 
|
|
||||||
1. Click `Theme settings` (ie. the paintbrush icon), expand the `STOREFRONT` section, enter your headless store domain, click the gray `Publish` button. 
|
|
||||||
1. Confirm the theme change by clicking the green `Save and publish` button. 
|
|
||||||
1. The headless theme should now be your current active theme. 
|
|
||||||
</details>
|
|
||||||
|
|
||||||
### Branding & Design
|
|
||||||
|
|
||||||
Since you're creating a headless Shopify store, you'll be in full control of your brand and design. However, there are still a few aspects we're leaving within Shopify's control.
|
|
||||||
|
|
||||||
- Checkout
|
|
||||||
- Emails
|
|
||||||
- Order status
|
|
||||||
- Order history
|
|
||||||
- Favicon (for any Shopify controlled pages)
|
|
||||||
|
|
||||||
You can use Shopify's admin to customize these pages to match your brand and design.
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Expand to view detailed walkthrough</summary>
|
|
||||||
|
|
||||||
#### Checkout, order status, and order history
|
|
||||||
|
|
||||||
1. Navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/settings/checkout`.
|
|
||||||
1. Click the green `Customize` button. 
|
|
||||||
1. Click `Branding` (ie. the paintbrush icon) and customize your brand. Please note, there are three steps / pages to the checkout flow. Use the dropdown to change pages and adjust branding as needed on each page. Click `Save` when you are done. 
|
|
||||||
1. Navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/settings/branding`.
|
|
||||||
1. Customize settings to match your brand. 
|
|
||||||
|
|
||||||
#### Emails
|
|
||||||
|
|
||||||
1. Navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/settings/email_settings`.
|
|
||||||
1. Customize settings to match your brand. 
|
|
||||||
|
|
||||||
#### Favicon
|
|
||||||
|
|
||||||
1. Navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/themes`.
|
|
||||||
1. Click the green `Customize` button. 
|
|
||||||
1. Click `Theme settings` (ie. the paintbrush icon), expand the `FAVICON` section, upload favicon, then click the `Save` button. 
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
### Configure webhooks for on-demand incremental static regeneration (ISR)
|
|
||||||
|
|
||||||
Utilizing [Shopify's webhooks](https://shopify.dev/docs/apps/webhooks), and listening for select [Shopify webhook event topics](https://shopify.dev/docs/api/admin-rest/2022-04/resources/webhook#event-topics), we can use [Next'js on-demand revalidation](https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating#using-on-demand-revalidation) to keep data fetches indefinitely cached until certain events in the Shopify store occur.
|
|
||||||
|
|
||||||
Next.js is pre-configured to listen for the following Shopify webhook events and automatically revalidate fetches.
|
|
||||||
|
|
||||||
- `collections/create`
|
|
||||||
- `collections/delete`
|
|
||||||
- `collections/update`
|
|
||||||
- `products/create`
|
|
||||||
- `products/delete`
|
|
||||||
- `products/update` (this also includes when variants are added, updated, and removed as well as when products are purchased so inventory and out of stocks can be updated)
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Expand to view detailed walkthrough</summary>
|
|
||||||
|
|
||||||
#### Setup secret for secure revalidation
|
|
||||||
|
|
||||||
1. Create your own secret or [generate a random UUID](https://www.uuidgenerator.net/guid).
|
|
||||||
1. Create a [Vercel Environment Variable](https://vercel.com/docs/concepts/projects/environment-variables) named `SHOPIFY_REVALIDATION_SECRET` and use the value from above.
|
|
||||||
|
|
||||||
#### Configure Shopify webhooks
|
|
||||||
|
|
||||||
1. Navigate to `https://[your-shopify-store-subdomain].myshopify.com/admin/settings/notifications`.
|
|
||||||
1. Add webhooks for all six event topics listed above. You can add more sets for other preview urls, environments, or local development. Append `?secret=[SECRET]` to each url, where `[SECRET]` is the secret you created above.  
|
|
||||||
|
|
||||||
#### Testing webhooks during local development
|
|
||||||
|
|
||||||
The easiest way to test webhooks while developing locally is to use [ngrok](https://ngrok.com).
|
|
||||||
|
|
||||||
1. [Install and configure ngrok](https://ngrok.com/download) (you will need to create an account).
|
|
||||||
1. Run your app locally, `npm run dev`.
|
|
||||||
1. In a separate terminal session, run `ngrok http 3000`.
|
|
||||||
1. Use the url generated by ngrok and add or update your webhook urls in Shopify.  
|
|
||||||
1. You can now make changes to your store and your local app should receive updates. You can also use the `Send test notification` button to trigger a generic webhook test. 
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
### Using Shopify as a CMS
|
|
||||||
|
|
||||||
Next.js Commerce is fully powered by Shopify in a truly headless and data driven way.
|
|
||||||
|
|
||||||
#### Products
|
|
||||||
|
|
||||||
`https://[your-shopify-store-subdomain].myshopify.com/admin/products`
|
|
||||||
|
|
||||||
Only `Active` products are shown. `Draft` products will not be shown until they are marked as `Active`.
|
|
||||||
|
|
||||||
`Active` products can still be hidden and not seen by navigating the site, by adding a `nextjs-frontend-hidden` tag on the product. This tag will also tell search engines to not index or crawl the product. The product is still directly accessible via url. This feature is great for "secret" products you only want to people you share the url with.
|
|
||||||
|
|
||||||
Product options and option combinations are driven from Shopify options and variants. When selecting options on the product detail page, other option and variant combinations will be visually validated and verified for availability, like Amazon does.
|
|
||||||
|
|
||||||
Products that are active and "out of stock" are still shown on the site, but the ability to add the product to the cart is disabled.
|
|
||||||
|
|
||||||
#### Collections
|
|
||||||
|
|
||||||
`https://[your-shopify-store-subdomain].myshopify.com/admin/collections`
|
|
||||||
|
|
||||||
Create whatever collections you want and configure them however you want. All available collections will show on the search page as filters on the left, with one exception...
|
|
||||||
|
|
||||||
Any collection names that start with the word "hidden" will not show up on the headless front end. The Next.js Commerce theme comes pre-configured to look for two hidden collections. Collections were chosen for this over tags so that order of products could be controlled (collections allow for manual ordering).
|
|
||||||
|
|
||||||
Create the following collections:
|
|
||||||
|
|
||||||
- `Hidden: Homepage Featured Items` -- Products in this collection are displayed in the three featured blocks on the homepage.
|
|
||||||
- `Hidden: Homepage Carousel` -- Products in this collection are displayed in the auto-scrolling carousel section on the homepage.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
#### Pages
|
|
||||||
|
|
||||||
`https://[your-shopify-store-subdomain].myshopify.com/admin/pages`
|
|
||||||
|
|
||||||
Next.js Commerce contains a dynamic `[page]` route. It will use the value to look for a corresponding page in Shopify. If a page is found, it will display its rich content using Tailwind's prose. If a page is not found, a 404 page is displayed.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
#### Navigation menus
|
|
||||||
|
|
||||||
`https://[your-shopify-store-subdomain].myshopify.com/admin/menus`
|
|
||||||
|
|
||||||
Next.js Commerce's header and footer navigation is pre-configured to be controlled by Shopify navigation menus. This means you have full control over what links go here. They can be to collections, pages, external links, and more.
|
|
||||||
|
|
||||||
Create the following navigation menus:
|
|
||||||
|
|
||||||
- `Next.js Frontend Header Menu` -- Menu items to be shown in the headless frontend header.
|
|
||||||
- `Next.js Frontend Footer Menu` -- Menu items to be shown in the headless frontend footer.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
#### SEO
|
|
||||||
|
|
||||||
Shopify's products, collections, pages, etc. allow you to create custom SEO titles and descriptions. Next.js Commerce is pre-configured to display these custom values, but also comes with sensible default fallbacks if they are not provided.
|
|
||||||
|
|
||||||

|
|
||||||
|
43
app/layout.tsx
Normal file
43
app/layout.tsx
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
import Navbar from 'components/layout/navbar';
|
||||||
|
import { GeistSans } from 'geist/font/sans';
|
||||||
|
import { ensureStartsWith } from 'lib/utils';
|
||||||
|
import { ReactNode } from 'react';
|
||||||
|
import './globals.css';
|
||||||
|
|
||||||
|
const { TWITTER_CREATOR, TWITTER_SITE, SITE_NAME } = process.env;
|
||||||
|
const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL
|
||||||
|
? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
|
||||||
|
: 'http://localhost:3000';
|
||||||
|
const twitterCreator = TWITTER_CREATOR ? ensureStartsWith(TWITTER_CREATOR, '@') : undefined;
|
||||||
|
const twitterSite = TWITTER_SITE ? ensureStartsWith(TWITTER_SITE, 'https://') : undefined;
|
||||||
|
|
||||||
|
export const metadata = {
|
||||||
|
metadataBase: new URL(baseUrl),
|
||||||
|
title: {
|
||||||
|
default: SITE_NAME!,
|
||||||
|
template: `%s | ${SITE_NAME}`
|
||||||
|
},
|
||||||
|
robots: {
|
||||||
|
follow: true,
|
||||||
|
index: true
|
||||||
|
},
|
||||||
|
...(twitterCreator &&
|
||||||
|
twitterSite && {
|
||||||
|
twitter: {
|
||||||
|
card: 'summary_large_image',
|
||||||
|
creator: twitterCreator,
|
||||||
|
site: twitterSite
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function RootLayout({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<html lang="en" className={GeistSans.variable}>
|
||||||
|
<body className="bg-neutral-50 text-black selection:bg-teal-300 dark:bg-neutral-900 dark:text-white dark:selection:bg-pink-500 dark:selection:text-white">
|
||||||
|
<Navbar />
|
||||||
|
<main>{children}</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
20
app/page.tsx
Normal file
20
app/page.tsx
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { Carousel } from 'components/carousel';
|
||||||
|
import { ThreeItemGrid } from 'components/grid/three-items';
|
||||||
|
import Footer from 'components/layout/footer';
|
||||||
|
|
||||||
|
export const metadata = {
|
||||||
|
description: 'High-performance ecommerce store built with Next.js, Vercel, and Shopify.',
|
||||||
|
openGraph: {
|
||||||
|
type: 'website'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function HomePage() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<ThreeItemGrid />
|
||||||
|
<Carousel />
|
||||||
|
<Footer />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
138
app/product/[handle]/page.tsx
Normal file
138
app/product/[handle]/page.tsx
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
import type { Metadata } from 'next';
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
|
|
||||||
|
import { GridTileImage } from 'components/grid/tile';
|
||||||
|
import Footer from 'components/layout/footer';
|
||||||
|
import { Gallery } from 'components/product/gallery';
|
||||||
|
import { ProductDescription } from 'components/product/product-description';
|
||||||
|
import { HIDDEN_PRODUCT_TAG } from 'lib/constants';
|
||||||
|
import { getProduct, getProductRecommendations } from 'lib/shopify';
|
||||||
|
import { Image } from 'lib/shopify/types';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
|
export async function generateMetadata({
|
||||||
|
params
|
||||||
|
}: {
|
||||||
|
params: { handle: string };
|
||||||
|
}): Promise<Metadata> {
|
||||||
|
const product = await getProduct(params.handle);
|
||||||
|
|
||||||
|
if (!product) return notFound();
|
||||||
|
|
||||||
|
const { url, width, height, altText: alt } = product.featuredImage || {};
|
||||||
|
const indexable = !product.tags.includes(HIDDEN_PRODUCT_TAG);
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: product.seo.title || product.title,
|
||||||
|
description: product.seo.description || product.description,
|
||||||
|
robots: {
|
||||||
|
index: indexable,
|
||||||
|
follow: indexable,
|
||||||
|
googleBot: {
|
||||||
|
index: indexable,
|
||||||
|
follow: indexable
|
||||||
|
}
|
||||||
|
},
|
||||||
|
openGraph: url
|
||||||
|
? {
|
||||||
|
images: [
|
||||||
|
{
|
||||||
|
url,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
alt
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
: null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ProductPage({ params }: { params: { handle: string } }) {
|
||||||
|
const product = await getProduct(params.handle);
|
||||||
|
|
||||||
|
if (!product) return notFound();
|
||||||
|
|
||||||
|
const productJsonLd = {
|
||||||
|
'@context': 'https://schema.org',
|
||||||
|
'@type': 'Product',
|
||||||
|
name: product.title,
|
||||||
|
description: product.description,
|
||||||
|
image: product.featuredImage.url,
|
||||||
|
offers: {
|
||||||
|
'@type': 'AggregateOffer',
|
||||||
|
availability: product.availableForSale
|
||||||
|
? 'https://schema.org/InStock'
|
||||||
|
: 'https://schema.org/OutOfStock',
|
||||||
|
priceCurrency: product.priceRange.minVariantPrice.currencyCode,
|
||||||
|
highPrice: product.priceRange.maxVariantPrice.amount,
|
||||||
|
lowPrice: product.priceRange.minVariantPrice.amount
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<script
|
||||||
|
type="application/ld+json"
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: JSON.stringify(productJsonLd)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div className="mx-auto max-w-screen-2xl px-4">
|
||||||
|
<div className="flex flex-col rounded-lg border border-neutral-200 bg-white p-8 dark:border-neutral-800 dark:bg-black md:p-12 lg:flex-row lg:gap-8">
|
||||||
|
<div className="h-full w-full basis-full lg:basis-4/6">
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<Gallery
|
||||||
|
images={product.images.map((image: Image) => ({
|
||||||
|
src: image.url,
|
||||||
|
altText: image.altText
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="basis-full lg:basis-2/6">
|
||||||
|
<ProductDescription product={product} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<RelatedProducts id={product.id} />
|
||||||
|
</div>
|
||||||
|
<Footer />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function RelatedProducts({ id }: { id: string }) {
|
||||||
|
const relatedProducts = await getProductRecommendations(id);
|
||||||
|
|
||||||
|
if (!relatedProducts.length) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="py-8">
|
||||||
|
<h2 className="mb-4 text-2xl font-bold">Related Products</h2>
|
||||||
|
<ul className="flex w-full gap-4 overflow-x-auto pt-1">
|
||||||
|
{relatedProducts.map((product) => (
|
||||||
|
<li
|
||||||
|
key={product.handle}
|
||||||
|
className="aspect-square w-full flex-none min-[475px]:w-1/2 sm:w-1/3 md:w-1/4 lg:w-1/5"
|
||||||
|
>
|
||||||
|
<Link className="relative h-full w-full" href={`/product/${product.handle}`}>
|
||||||
|
<GridTileImage
|
||||||
|
alt={product.title}
|
||||||
|
label={{
|
||||||
|
title: product.title,
|
||||||
|
amount: product.priceRange.maxVariantPrice.amount,
|
||||||
|
currencyCode: product.priceRange.maxVariantPrice.currencyCode
|
||||||
|
}}
|
||||||
|
src={product.featuredImage?.url}
|
||||||
|
fill
|
||||||
|
sizes="(min-width: 1024px) 20vw, (min-width: 768px) 25vw, (min-width: 640px) 33vw, (min-width: 475px) 50vw, 100vw"
|
||||||
|
/>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
@ -1,9 +1,11 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
|
import { TAGS } from 'lib/constants';
|
||||||
import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/shopify';
|
import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/shopify';
|
||||||
|
import { revalidateTag } from 'next/cache';
|
||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
|
|
||||||
export const addItem = async (variantId: string | undefined): Promise<String | undefined> => {
|
export async function addItem(prevState: any, selectedVariantId: string | undefined) {
|
||||||
let cartId = cookies().get('cartId')?.value;
|
let cartId = cookies().get('cartId')?.value;
|
||||||
let cart;
|
let cart;
|
||||||
|
|
||||||
@ -17,16 +19,17 @@ export const addItem = async (variantId: string | undefined): Promise<String | u
|
|||||||
cookies().set('cartId', cartId);
|
cookies().set('cartId', cartId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!variantId) {
|
if (!selectedVariantId) {
|
||||||
return 'Missing product variant ID';
|
return 'Missing product variant ID';
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await addToCart(cartId, [{ merchandiseId: variantId, quantity: 1 }]);
|
await addToCart(cartId, [{ merchandiseId: selectedVariantId, quantity: 1 }]);
|
||||||
|
revalidateTag(TAGS.cart);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return 'Error adding item to cart';
|
return 'Error adding item to cart';
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const addItems = async ({
|
export const addItems = async ({
|
||||||
variantId,
|
variantId,
|
||||||
@ -59,34 +62,44 @@ export const addItems = async ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const removeItem = async (lineId: string): Promise<String | undefined> => {
|
export async function removeItem(prevState: any, lineId: string) {
|
||||||
const cartId = cookies().get('cartId')?.value;
|
const cartId = cookies().get('cartId')?.value;
|
||||||
|
|
||||||
if (!cartId) {
|
if (!cartId) {
|
||||||
return 'Missing cart ID';
|
return 'Missing cart ID';
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await removeFromCart(cartId, [lineId]);
|
await removeFromCart(cartId, [lineId]);
|
||||||
|
revalidateTag(TAGS.cart);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return 'Error removing item from cart';
|
return 'Error removing item from cart';
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const updateItemQuantity = async ({
|
export async function updateItemQuantity(
|
||||||
lineId,
|
prevState: any,
|
||||||
variantId,
|
payload: {
|
||||||
quantity
|
|
||||||
}: {
|
|
||||||
lineId: string;
|
lineId: string;
|
||||||
variantId: string;
|
variantId: string;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
}): Promise<String | undefined> => {
|
}
|
||||||
|
) {
|
||||||
const cartId = cookies().get('cartId')?.value;
|
const cartId = cookies().get('cartId')?.value;
|
||||||
|
|
||||||
if (!cartId) {
|
if (!cartId) {
|
||||||
return 'Missing cart ID';
|
return 'Missing cart ID';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { lineId, variantId, quantity } = payload;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (quantity === 0) {
|
||||||
|
await removeFromCart(cartId, [lineId]);
|
||||||
|
revalidateTag(TAGS.cart);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
await updateCart(cartId, [
|
await updateCart(cartId, [
|
||||||
{
|
{
|
||||||
id: lineId,
|
id: lineId,
|
||||||
@ -94,7 +107,8 @@ export const updateItemQuantity = async ({
|
|||||||
quantity
|
quantity
|
||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
|
revalidateTag(TAGS.cart);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return 'Error updating item quantity';
|
return 'Error updating item quantity';
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
@ -5,7 +5,9 @@ import { addItem } from 'components/cart/actions';
|
|||||||
import LoadingDots from 'components/loading-dots';
|
import LoadingDots from 'components/loading-dots';
|
||||||
import { ProductVariant } from 'lib/shopify/types';
|
import { ProductVariant } from 'lib/shopify/types';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
import router from 'next/router';
|
||||||
|
import { title } from 'process';
|
||||||
import { useTransition } from 'react';
|
import { useTransition } from 'react';
|
||||||
|
|
||||||
export function AddToCart({
|
export function AddToCart({
|
||||||
@ -15,7 +17,7 @@ export function AddToCart({
|
|||||||
variants: ProductVariant[];
|
variants: ProductVariant[];
|
||||||
availableForSale: boolean;
|
availableForSale: boolean;
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const [message, formAction] = useFormState(addItem, null);
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const t = useTranslations('Index');
|
const t = useTranslations('Index');
|
||||||
|
|
||||||
@ -27,11 +29,7 @@ export function AddToCart({
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
const selectedVariantId = variant?.id || defaultVariantId;
|
const selectedVariantId = variant?.id || defaultVariantId;
|
||||||
const title = !availableForSale
|
const actionWithVariant = formAction.bind(null, selectedVariantId);
|
||||||
? 'Out of stock'
|
|
||||||
: !selectedVariantId
|
|
||||||
? 'Please select options'
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
|
@ -1,40 +1,31 @@
|
|||||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
'use client';
|
||||||
import LoadingDots from 'components/loading-dots';
|
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
|
|
||||||
|
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||||
import clsx from 'clsx';
|
import clsx from 'clsx';
|
||||||
import { removeItem } from 'components/cart/actions';
|
import { removeItem } from 'components/cart/actions';
|
||||||
|
import LoadingDots from 'components/loading-dots';
|
||||||
import type { CartItem } from 'lib/shopify/types';
|
import type { CartItem } from 'lib/shopify/types';
|
||||||
import { useTransition } from 'react';
|
import { useFormState, useFormStatus } from 'react-dom';
|
||||||
|
|
||||||
export default function DeleteItemButton({ item }: { item: CartItem }) {
|
function SubmitButton() {
|
||||||
const router = useRouter();
|
const { pending } = useFormStatus();
|
||||||
const [isPending, startTransition] = useTransition();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
aria-label="Remove cart item"
|
type="submit"
|
||||||
onClick={() => {
|
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
|
||||||
startTransition(async () => {
|
if (pending) e.preventDefault();
|
||||||
const error = await removeItem(item.id);
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
// Trigger the error boundary in the root error.js
|
|
||||||
throw new Error(error.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
router.refresh();
|
|
||||||
});
|
|
||||||
}}
|
}}
|
||||||
disabled={isPending}
|
aria-label="Remove cart item"
|
||||||
|
aria-disabled={pending}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
'ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-dark transition-all duration-200',
|
'ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-dark transition-all duration-200',
|
||||||
{
|
{
|
||||||
'cursor-not-allowed px-0': isPending
|
'cursor-not-allowed px-0': pending
|
||||||
}
|
}
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isPending ? (
|
{pending ? (
|
||||||
<LoadingDots className="bg-white" />
|
<LoadingDots className="bg-white" />
|
||||||
) : (
|
) : (
|
||||||
<XMarkIcon className="mx-[1px] h-4 w-4 text-white transition-opacity duration-150 hover:opacity-60 dark:text-black" />
|
<XMarkIcon className="mx-[1px] h-4 w-4 text-white transition-opacity duration-150 hover:opacity-60 dark:text-black" />
|
||||||
@ -42,3 +33,18 @@ export default function DeleteItemButton({ item }: { item: CartItem }) {
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function DeleteItemButton({ item }: { item: CartItem }) {
|
||||||
|
const [message, formAction] = useFormState(removeItem, null);
|
||||||
|
const itemId = item.id;
|
||||||
|
const actionWithVariant = formAction.bind(null, itemId);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form action={actionWithVariant}>
|
||||||
|
<SubmitButton />
|
||||||
|
<p aria-live="polite" className="sr-only" role="status">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
@ -1,54 +1,32 @@
|
|||||||
import { useRouter } from 'next/navigation';
|
'use client';
|
||||||
import { useTransition } from 'react';
|
|
||||||
|
|
||||||
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 { removeItem, updateItemQuantity } from 'components/cart/actions';
|
import { updateItemQuantity } from 'components/cart/actions';
|
||||||
import LoadingDots from 'components/loading-dots';
|
import LoadingDots from 'components/loading-dots';
|
||||||
import type { CartItem } from 'lib/shopify/types';
|
import type { CartItem } from 'lib/shopify/types';
|
||||||
|
import { useFormState, useFormStatus } from 'react-dom';
|
||||||
|
|
||||||
export default function EditItemQuantityButton({
|
function SubmitButton({ type }: { type: 'plus' | 'minus' }) {
|
||||||
item,
|
const { pending } = useFormStatus();
|
||||||
type
|
|
||||||
}: {
|
|
||||||
item: CartItem;
|
|
||||||
type: 'plus' | 'minus';
|
|
||||||
}) {
|
|
||||||
const router = useRouter();
|
|
||||||
const [isPending, startTransition] = useTransition();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
|
type="submit"
|
||||||
onClick={() => {
|
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
|
||||||
startTransition(async () => {
|
if (pending) e.preventDefault();
|
||||||
const error =
|
|
||||||
type === 'minus' && item.quantity - 1 === 0
|
|
||||||
? await removeItem(item.id)
|
|
||||||
: await updateItemQuantity({
|
|
||||||
lineId: item.id,
|
|
||||||
variantId: item.merchandise.id,
|
|
||||||
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
|
|
||||||
});
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
// Trigger the error boundary in the root error.js
|
|
||||||
throw new Error(error.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
router.refresh();
|
|
||||||
});
|
|
||||||
}}
|
}}
|
||||||
disabled={isPending}
|
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
|
||||||
|
aria-disabled={pending}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
'ease flex h-full min-w-[36px] max-w-[36px] flex-none items-center justify-center rounded-full px-2 transition-all duration-200 hover:border-neutral-800 hover:opacity-80',
|
'ease flex h-full min-w-[36px] max-w-[36px] flex-none items-center justify-center rounded-full px-2 transition-all duration-200 hover:border-neutral-800 hover:opacity-80',
|
||||||
{
|
{
|
||||||
'cursor-not-allowed': isPending,
|
'cursor-not-allowed': pending,
|
||||||
'ml-auto': type === 'minus'
|
'ml-auto': type === 'minus'
|
||||||
}
|
}
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isPending ? (
|
{pending ? (
|
||||||
<LoadingDots className="bg-black dark:bg-white" />
|
<LoadingDots className="bg-black dark:bg-white" />
|
||||||
) : type === 'plus' ? (
|
) : type === 'plus' ? (
|
||||||
<PlusIcon className="h-4 w-4 dark:text-neutral-500" />
|
<PlusIcon className="h-4 w-4 dark:text-neutral-500" />
|
||||||
@ -58,3 +36,22 @@ export default function EditItemQuantityButton({
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function EditItemQuantityButton({ item, type }: { item: CartItem; type: 'plus' | 'minus' }) {
|
||||||
|
const [message, formAction] = useFormState(updateItemQuantity, null);
|
||||||
|
const payload = {
|
||||||
|
lineId: item.id,
|
||||||
|
variantId: item.merchandise.id,
|
||||||
|
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
|
||||||
|
};
|
||||||
|
const actionWithVariant = formAction.bind(null, payload);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form action={actionWithVariant}>
|
||||||
|
<SubmitButton type={type} />
|
||||||
|
<p aria-live="polite" className="sr-only" role="status">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
@ -13,8 +13,8 @@ import Image from 'next/image';
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { Fragment, useEffect, useRef, useState } from 'react';
|
import { Fragment, useEffect, useRef, useState } from 'react';
|
||||||
import CloseCart from './close-cart';
|
import CloseCart from './close-cart';
|
||||||
import DeleteItemButton from './delete-item-button';
|
import { DeleteItemButton } from './delete-item-button';
|
||||||
import EditItemQuantityButton from './edit-item-quantity-button';
|
import { EditItemQuantityButton } from './edit-item-quantity-button';
|
||||||
import OpenCart from './open-cart';
|
import OpenCart from './open-cart';
|
||||||
import { PromotedCartItem } from './promoted-cart-item';
|
import { PromotedCartItem } from './promoted-cart-item';
|
||||||
|
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
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, useEffect, useState } from 'react';
|
import { Fragment, Suspense, useEffect, useState } from 'react';
|
||||||
|
|
||||||
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline';
|
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||||
import { Menu } from 'lib/shopify/types';
|
import { Menu } from 'lib/shopify/types';
|
||||||
@ -72,7 +72,9 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div className="mb-4 w-full">
|
<div className="mb-4 w-full">
|
||||||
|
<Suspense fallback={null}>
|
||||||
<Search />
|
<Search />
|
||||||
|
</Suspense>
|
||||||
</div>
|
</div>
|
||||||
{menu.length ? (
|
{menu.length ? (
|
||||||
<ul className="flex w-full flex-col">
|
<ul className="flex w-full flex-col">
|
||||||
|
@ -1,19 +1,12 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
|
|
||||||
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
|
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
|
||||||
import { createUrl } from 'lib/utils';
|
import { createUrl } from 'lib/utils';
|
||||||
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
|
||||||
export default function Search() {
|
export default function Search() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const [searchValue, setSearchValue] = useState('');
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setSearchValue(searchParams?.get('q') || '');
|
|
||||||
}, [searchParams, setSearchValue]);
|
|
||||||
|
|
||||||
function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@ -34,12 +27,12 @@ export default function Search() {
|
|||||||
return (
|
return (
|
||||||
<form onSubmit={onSubmit} className="relative w-full max-w-[550px] lg:w-80 xl:w-full">
|
<form onSubmit={onSubmit} className="relative w-full max-w-[550px] lg:w-80 xl:w-full">
|
||||||
<input
|
<input
|
||||||
|
key={searchParams?.get('q')}
|
||||||
type="text"
|
type="text"
|
||||||
name="search"
|
name="search"
|
||||||
placeholder="Search for products..."
|
placeholder="Search for products..."
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
value={searchValue}
|
defaultValue={searchParams?.get('q') || ''}
|
||||||
onChange={(e) => setSearchValue(e.target.value)}
|
|
||||||
className="w-full rounded-lg border bg-white px-4 py-2 text-sm text-black placeholder:text-neutral-500 dark:border-neutral-800 dark:bg-transparent dark:text-white dark:placeholder:text-neutral-400"
|
className="w-full rounded-lg border bg-white px-4 py-2 text-sm text-black placeholder:text-neutral-500 dark:border-neutral-800 dark:bg-transparent dark:text-white dark:placeholder:text-neutral-400"
|
||||||
/>
|
/>
|
||||||
<div className="absolute right-0 top-0 mr-3 flex h-full items-center">
|
<div className="absolute right-0 top-0 mr-3 flex h-full items-center">
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import { SortFilterItem } from 'lib/constants';
|
import { SortFilterItem } from 'lib/constants';
|
||||||
|
import { Suspense } from 'react';
|
||||||
import FilterItemDropdown from './dropdown';
|
import FilterItemDropdown from './dropdown';
|
||||||
import { FilterItem } from './item';
|
import { FilterItem } from './item';
|
||||||
|
|
||||||
@ -19,12 +20,20 @@ export default function FilterList({ list, title }: { list: ListItem[]; title?:
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<nav>
|
<nav>
|
||||||
{title ? <h3 className="hidden text-xs text-neutral-500 md:block">{title}</h3> : null}
|
{title ? (
|
||||||
|
<h3 className="hidden text-xs text-neutral-500 dark:text-neutral-400 md:block">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
) : null}
|
||||||
<ul className="hidden md:block">
|
<ul className="hidden md:block">
|
||||||
|
<Suspense fallback={null}>
|
||||||
<FilterItemList list={list} />
|
<FilterItemList list={list} />
|
||||||
|
</Suspense>
|
||||||
</ul>
|
</ul>
|
||||||
<ul className="md:hidden">
|
<ul className="md:hidden">
|
||||||
|
<Suspense fallback={null}>
|
||||||
<FilterItemDropdown list={list} />
|
<FilterItemDropdown list={list} />
|
||||||
|
</Suspense>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
</>
|
</>
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { ImageResponse } from 'next/server';
|
import { ImageResponse } from 'next/og';
|
||||||
import Logo from './icons/logo';
|
import Logo from './icons/logo';
|
||||||
|
|
||||||
export type Props = {
|
export type Props = {
|
||||||
|
@ -3,8 +3,7 @@
|
|||||||
import clsx from 'clsx';
|
import clsx from 'clsx';
|
||||||
import { ProductOption, ProductVariant } from 'lib/shopify/types';
|
import { ProductOption, ProductVariant } from 'lib/shopify/types';
|
||||||
import { createUrl } from 'lib/utils';
|
import { createUrl } from 'lib/utils';
|
||||||
import Link from 'next/link';
|
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
||||||
import { usePathname, useSearchParams } from 'next/navigation';
|
|
||||||
|
|
||||||
type Combination = {
|
type Combination = {
|
||||||
id: string;
|
id: string;
|
||||||
@ -19,6 +18,7 @@ export function VariantSelector({
|
|||||||
options: ProductOption[];
|
options: ProductOption[];
|
||||||
variants: ProductVariant[];
|
variants: ProductVariant[];
|
||||||
}) {
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const hasNoOptionsOrJustOneOption =
|
const hasNoOptionsOrJustOneOption =
|
||||||
@ -76,17 +76,14 @@ export function VariantSelector({
|
|||||||
// The option is active if it's in the url params.
|
// The option is active if it's in the url params.
|
||||||
const isActive = searchParams.get(optionNameLowerCase) === value;
|
const isActive = searchParams.get(optionNameLowerCase) === value;
|
||||||
|
|
||||||
// You can't disable a link, so we need to render something that isn't clickable.
|
|
||||||
const DynamicTag = isAvailableForSale ? Link : 'p';
|
|
||||||
const dynamicProps = {
|
|
||||||
...(isAvailableForSale && { scroll: false })
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DynamicTag
|
<button
|
||||||
key={value}
|
key={value}
|
||||||
aria-disabled={!isAvailableForSale}
|
aria-disabled={!isAvailableForSale}
|
||||||
href={optionUrl}
|
disabled={!isAvailableForSale}
|
||||||
|
onClick={() => {
|
||||||
|
router.replace(optionUrl, { scroll: false });
|
||||||
|
}}
|
||||||
title={`${option.name} ${value}${!isAvailableForSale ? ' (Out of Stock)' : ''}`}
|
title={`${option.name} ${value}${!isAvailableForSale ? ' (Out of Stock)' : ''}`}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
'flex min-w-[48px] items-center justify-center rounded-full border bg-white px-2 py-1 text-sm text-black',
|
'flex min-w-[48px] items-center justify-center rounded-full border bg-white px-2 py-1 text-sm text-black',
|
||||||
@ -98,10 +95,9 @@ export function VariantSelector({
|
|||||||
!isAvailableForSale
|
!isAvailableForSale
|
||||||
}
|
}
|
||||||
)}
|
)}
|
||||||
{...dynamicProps}
|
|
||||||
>
|
>
|
||||||
{value}
|
{value}
|
||||||
</DynamicTag>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</dd>
|
</dd>
|
||||||
|
@ -1,15 +1,12 @@
|
|||||||
import Footer from 'components/layout/footer';
|
import Footer from 'components/layout/footer';
|
||||||
import { Suspense } from 'react';
|
|
||||||
|
|
||||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<Suspense>
|
<>
|
||||||
<div className="w-full">
|
<div className="w-full">
|
||||||
<div className="mx-8 max-w-2xl py-20 sm:mx-auto">
|
<div className="mx-8 max-w-2xl py-20 sm:mx-auto">{children}</div>
|
||||||
<Suspense>{children}</Suspense>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<Footer />
|
<Footer />
|
||||||
</Suspense>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -5,9 +5,6 @@ import Prose from 'components/prose';
|
|||||||
import { getPage } from 'lib/shopify';
|
import { getPage } from 'lib/shopify';
|
||||||
import { notFound } from 'next/navigation';
|
import { notFound } from 'next/navigation';
|
||||||
|
|
||||||
export const runtime = 'edge';
|
|
||||||
export const revalidate = 43200; // 12 hours in seconds
|
|
||||||
|
|
||||||
export async function generateMetadata({
|
export async function generateMetadata({
|
||||||
params
|
params
|
||||||
}: {
|
}: {
|
||||||
|
@ -6,9 +6,6 @@ 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 { defaultSort, sorting } from 'lib/constants';
|
||||||
|
|
||||||
export const runtime = 'edge';
|
|
||||||
export const revalidate = 300; // 5 minutes in seconds
|
|
||||||
|
|
||||||
export async function generateMetadata({
|
export async function generateMetadata({
|
||||||
params
|
params
|
||||||
}: {
|
}: {
|
||||||
|
@ -2,11 +2,10 @@ import Footer from 'components/layout/footer';
|
|||||||
import Collections from 'components/layout/search/collections';
|
import Collections from 'components/layout/search/collections';
|
||||||
import FilterList from 'components/layout/search/filter';
|
import FilterList from 'components/layout/search/filter';
|
||||||
import { sorting } from 'lib/constants';
|
import { sorting } from 'lib/constants';
|
||||||
import { Suspense } from 'react';
|
|
||||||
|
|
||||||
export default function SearchLayout({ children }: { children: React.ReactNode }) {
|
export default function SearchLayout({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<Suspense>
|
<>
|
||||||
<div className="mx-auto flex max-w-screen-xl flex-col gap-8 px-4 pb-4 text-black dark:text-white md:flex-row">
|
<div className="mx-auto flex max-w-screen-xl flex-col gap-8 px-4 pb-4 text-black dark:text-white md:flex-row">
|
||||||
<div className="order-first w-full flex-none md:max-w-[125px]">
|
<div className="order-first w-full flex-none md:max-w-[125px]">
|
||||||
<Collections />
|
<Collections />
|
||||||
@ -17,6 +16,6 @@ export default function SearchLayout({ children }: { children: React.ReactNode }
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Footer />
|
<Footer />
|
||||||
</Suspense>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -3,9 +3,6 @@ import ProductGridItems from 'components/layout/product-grid-items';
|
|||||||
import { defaultSort, sorting } from 'lib/constants';
|
import { defaultSort, sorting } from 'lib/constants';
|
||||||
import { getProducts } from 'lib/shopify';
|
import { getProducts } from 'lib/shopify';
|
||||||
|
|
||||||
export const runtime = 'edge';
|
|
||||||
export const revalidate = 300; // 5 minutes in seconds
|
|
||||||
|
|
||||||
export const metadata = {
|
export const metadata = {
|
||||||
title: 'Search',
|
title: 'Search',
|
||||||
description: 'Search for products in the store.'
|
description: 'Search for products in the store.'
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import { getCollections, getPages, getProducts } from 'lib/shopify';
|
import { getCollections, getPages, getProducts } from 'lib/shopify';
|
||||||
|
import { validateEnvironmentVariables } from 'lib/utils';
|
||||||
import { MetadataRoute } from 'next';
|
import { MetadataRoute } from 'next';
|
||||||
|
|
||||||
type Route = {
|
type Route = {
|
||||||
@ -11,6 +12,8 @@ const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL
|
|||||||
: 'http://localhost:3000';
|
: 'http://localhost:3000';
|
||||||
|
|
||||||
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||||
|
validateEnvironmentVariables();
|
||||||
|
|
||||||
const routesMap = [''].map((route) => ({
|
const routesMap = [''].map((route) => ({
|
||||||
url: `${baseUrl}${route}`,
|
url: `${baseUrl}${route}`,
|
||||||
lastModified: new Date().toISOString()
|
lastModified: new Date().toISOString()
|
||||||
|
@ -22,7 +22,8 @@ export const sorting: SortFilterItem[] = [
|
|||||||
|
|
||||||
export const TAGS = {
|
export const TAGS = {
|
||||||
collections: 'collections',
|
collections: 'collections',
|
||||||
products: 'products'
|
products: 'products',
|
||||||
|
cart: 'cart'
|
||||||
};
|
};
|
||||||
|
|
||||||
export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden';
|
export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden';
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
import { HIDDEN_PRODUCT_TAG, SHOPIFY_GRAPHQL_API_ENDPOINT, TAGS } from 'lib/constants';
|
import { HIDDEN_PRODUCT_TAG, SHOPIFY_GRAPHQL_API_ENDPOINT, TAGS } from 'lib/constants';
|
||||||
import { isShopifyError } from 'lib/type-guards';
|
import { isShopifyError } from 'lib/type-guards';
|
||||||
|
import { ensureStartsWith } from 'lib/utils';
|
||||||
import { revalidateTag } from 'next/cache';
|
import { revalidateTag } from 'next/cache';
|
||||||
import { headers } from 'next/headers';
|
import { headers } from 'next/headers';
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
@ -55,7 +56,9 @@ import {
|
|||||||
ShopifyUpdateCartOperation
|
ShopifyUpdateCartOperation
|
||||||
} from './types';
|
} from './types';
|
||||||
|
|
||||||
const domain = `https://${process.env.SHOPIFY_STORE_DOMAIN!}`;
|
const domain = process.env.SHOPIFY_STORE_DOMAIN
|
||||||
|
? ensureStartsWith(process.env.SHOPIFY_STORE_DOMAIN, 'https://')
|
||||||
|
: '';
|
||||||
const endpoint = `${domain}${SHOPIFY_GRAPHQL_API_ENDPOINT}`;
|
const endpoint = `${domain}${SHOPIFY_GRAPHQL_API_ENDPOINT}`;
|
||||||
const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN!;
|
const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN!;
|
||||||
|
|
||||||
@ -103,6 +106,7 @@ export async function shopifyFetch<T>({
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isShopifyError(e)) {
|
if (isShopifyError(e)) {
|
||||||
throw {
|
throw {
|
||||||
|
cause: e.cause?.toString() || 'unknown',
|
||||||
status: e.status || 500,
|
status: e.status || 500,
|
||||||
message: e.message,
|
message: e.message,
|
||||||
query
|
query
|
||||||
@ -273,6 +277,7 @@ export async function getCart(cartId: string): Promise<Cart | undefined> {
|
|||||||
const res = await shopifyFetch<ShopifyCartOperation>({
|
const res = await shopifyFetch<ShopifyCartOperation>({
|
||||||
query: getCartQuery,
|
query: getCartQuery,
|
||||||
variables: { cartId },
|
variables: { cartId },
|
||||||
|
tags: [TAGS.cart],
|
||||||
cache: 'no-store'
|
cache: 'no-store'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
export interface ShopifyErrorLike {
|
export interface ShopifyErrorLike {
|
||||||
status: number;
|
status: number;
|
||||||
message: Error;
|
message: Error;
|
||||||
|
cause?: Error;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isObject = (object: unknown): object is Record<string, unknown> => {
|
export const isObject = (object: unknown): object is Record<string, unknown> => {
|
||||||
|
31
lib/utils.ts
31
lib/utils.ts
@ -6,3 +6,34 @@ export const createUrl = (pathname: string, params: URLSearchParams | ReadonlyUR
|
|||||||
|
|
||||||
return `${pathname}${queryString}`;
|
return `${pathname}${queryString}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const ensureStartsWith = (stringToCheck: string, startsWith: string) =>
|
||||||
|
stringToCheck.startsWith(startsWith) ? stringToCheck : `${startsWith}${stringToCheck}`;
|
||||||
|
|
||||||
|
export const validateEnvironmentVariables = () => {
|
||||||
|
const requiredEnvironmentVariables = ['SHOPIFY_STORE_DOMAIN', 'SHOPIFY_STOREFRONT_ACCESS_TOKEN'];
|
||||||
|
const missingEnvironmentVariables = [] as string[];
|
||||||
|
|
||||||
|
requiredEnvironmentVariables.forEach((envVar) => {
|
||||||
|
if (!process.env[envVar]) {
|
||||||
|
missingEnvironmentVariables.push(envVar);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (missingEnvironmentVariables.length) {
|
||||||
|
throw new Error(
|
||||||
|
`The following environment variables are missing. Your site will not work without them. Read more: https://vercel.com/docs/integrations/shopify#configure-environment-variables\n\n${missingEnvironmentVariables.join(
|
||||||
|
'\n'
|
||||||
|
)}\n`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
process.env.SHOPIFY_STORE_DOMAIN?.includes('[') ||
|
||||||
|
process.env.SHOPIFY_STORE_DOMAIN?.includes(']')
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'Your `SHOPIFY_STORE_DOMAIN` environment variable includes brackets (ie. `[` and / or `]`). Your site will not work with them there. Please remove them.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
@ -5,7 +5,7 @@ module.exports = {
|
|||||||
ignoreDuringBuilds: true
|
ignoreDuringBuilds: true
|
||||||
},
|
},
|
||||||
experimental: {
|
experimental: {
|
||||||
serverActions: true
|
ppr: true
|
||||||
},
|
},
|
||||||
images: {
|
images: {
|
||||||
formats: ['image/avif', 'image/webp'],
|
formats: ['image/avif', 'image/webp'],
|
||||||
@ -16,5 +16,14 @@ module.exports = {
|
|||||||
pathname: '/s/files/**'
|
pathname: '/s/files/**'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
async redirects() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
source: '/password',
|
||||||
|
destination: '/',
|
||||||
|
permanent: true
|
||||||
|
}
|
||||||
|
];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -23,7 +23,7 @@
|
|||||||
"*": "prettier --write --ignore-unknown"
|
"*": "prettier --write --ignore-unknown"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@headlessui/react": "^1.7.15",
|
"@headlessui/react": "^1.7.17",
|
||||||
"@heroicons/react": "^2.0.18",
|
"@heroicons/react": "^2.0.18",
|
||||||
"@thgh/next-gtm": "^0.1.4",
|
"@thgh/next-gtm": "^0.1.4",
|
||||||
"@types/react-gtm-module": "^2.0.1",
|
"@types/react-gtm-module": "^2.0.1",
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
/** @type {import('prettier').Config} */
|
||||||
module.exports = {
|
module.exports = {
|
||||||
singleQuote: true,
|
singleQuote: true,
|
||||||
arrowParens: 'always',
|
arrowParens: 'always',
|
||||||
|
Loading…
x
Reference in New Issue
Block a user