mirror of
https://github.com/vercel/commerce.git
synced 2025-07-23 04:36:49 +00:00
Next.js Commerce refresh. (#966)
We're making some updates to Next.js Commerce. Everything prior to this commit marks what we're calling [`v1`](https://github.com/vercel/commerce/releases/tag/v1) as a point in time to be able to reference and still use going into the future. The current architecture of Commerce is a multi-vendor, interoperable solution, including:
- [Shopify](https://shopify.vercel.store/)
- [Swell](https://swell.vercel.store/)
- [BigCommerce](https://bigcommerce.vercel.store/)
- [Vendure](https://vendure.vercel.store/)
- [Saleor](https://saleor.vercel.store/)
- [Ordercloud](https://ordercloud.vercel.store/)
- [Spree](https://spree.vercel.store/)
- [Kibo Commerce](https://kibocommerce.vercel.store/)
- [Commerce.js](https://commercejs.vercel.store/)
- [SalesForce Cloud Commerce](https://salesforce-cloud-commerce.vercel.store/)
All features can be toggled on or off, and it's easy to change between commerce providers. To support this, we needed to create a ["commerce metaframework"](d1d9e8c434/packages/commerce/new-provider.md
) where providers could confirm to an API spec to add support for Next.js Commerce. While this worked and was successful for `v1`, we have different design goals and ambitions for `v2`.
**What You Need To Know**
- `v1` will not be updated moving forward. If you need to reference `v1`, you will still be able to clone and deploy the version tagged at this release.
- `v2` will be shifting to be a single provider vs. provider agnostic. Other providers are welcome to fork this repository and swap out the underlying `lib/` implementation that connects to the selected commerce provider (Shopify). This architecture was chosen to reduce the surface area of the codebase, remove the intermediate metaframework layer for provider-interoperability, and enable usage with the latest Next.js and React features.
- We will be sharing more about `v2` in the future as we continue to iterate before the marked release.
This commit is contained in:
64
components/cart/button.tsx
Normal file
64
components/cart/button.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCookies } from 'react-cookie';
|
||||
|
||||
import CartIcon from 'components/icons/cart';
|
||||
import CartModal from './modal';
|
||||
|
||||
import type { Cart } from 'lib/shopify/types';
|
||||
|
||||
export default function CartButton({
|
||||
cart,
|
||||
cartIdUpdated
|
||||
}: {
|
||||
cart: Cart;
|
||||
cartIdUpdated: boolean;
|
||||
}) {
|
||||
const [, setCookie] = useCookies(['cartId']);
|
||||
const [cartIsOpen, setCartIsOpen] = useState(false);
|
||||
const quantityRef = useRef(cart.totalQuantity);
|
||||
|
||||
// Temporary hack to update the `cartId` cookie when it changes since we cannot update it
|
||||
// on the server-side (yet).
|
||||
useEffect(() => {
|
||||
if (cartIdUpdated) {
|
||||
setCookie('cartId', cart.id, {
|
||||
path: '/',
|
||||
sameSite: 'strict',
|
||||
secure: process.env.NODE_ENV === 'production'
|
||||
});
|
||||
}
|
||||
return;
|
||||
}, [setCookie, cartIdUpdated, cart.id]);
|
||||
|
||||
useEffect(() => {
|
||||
// Open cart modal when when quantity changes.
|
||||
if (cart.totalQuantity !== quantityRef.current) {
|
||||
// But only if it's not already open (quantity also changes when editing items in cart).
|
||||
if (!cartIsOpen) {
|
||||
setCartIsOpen(true);
|
||||
}
|
||||
|
||||
// Always update the quantity reference
|
||||
quantityRef.current = cart.totalQuantity;
|
||||
}
|
||||
}, [cartIsOpen, cart.totalQuantity, quantityRef]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<CartModal isOpen={cartIsOpen} onClose={() => setCartIsOpen(false)} cart={cart} />
|
||||
|
||||
<button
|
||||
aria-label="Open cart"
|
||||
onClick={() => {
|
||||
setCartIsOpen(true);
|
||||
}}
|
||||
className="relative top-0 right-0"
|
||||
data-testid="open-cart"
|
||||
>
|
||||
<CartIcon quantity={cart.totalQuantity} />
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
50
components/cart/delete-item-button.tsx
Normal file
50
components/cart/delete-item-button.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import CloseIcon from 'components/icons/close';
|
||||
import LoadingDots from 'components/loading-dots';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { startTransition, useState } from 'react';
|
||||
|
||||
import type { CartItem } from 'lib/shopify/types';
|
||||
|
||||
export default function DeleteItemButton({ item }: { item: CartItem }) {
|
||||
const router = useRouter();
|
||||
const [removing, setRemoving] = useState(false);
|
||||
|
||||
async function handleRemove() {
|
||||
setRemoving(true);
|
||||
|
||||
const response = await fetch(`/api/cart`, {
|
||||
method: 'DELETE',
|
||||
body: JSON.stringify({
|
||||
lineId: item.id
|
||||
})
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.error) {
|
||||
alert(data.error);
|
||||
return;
|
||||
}
|
||||
|
||||
setRemoving(false);
|
||||
|
||||
startTransition(() => {
|
||||
router.refresh();
|
||||
});
|
||||
}
|
||||
return (
|
||||
<button
|
||||
aria-label="Remove cart item"
|
||||
onClick={handleRemove}
|
||||
disabled={removing}
|
||||
className={`${
|
||||
removing ? 'cursor-not-allowed' : ''
|
||||
} mr-2 flex h-8 w-8 items-center justify-center border border-black/40 bg-black/0 hover:bg-black/10 dark:border-white/40 dark:bg-white/0 dark:hover:bg-white/10`}
|
||||
>
|
||||
{removing ? (
|
||||
<LoadingDots className="bg-white dark:bg-black" />
|
||||
) : (
|
||||
<CloseIcon className="hover:text-accent-3 h-6" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
62
components/cart/edit-item-quantity-button.tsx
Normal file
62
components/cart/edit-item-quantity-button.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { startTransition, useState } from 'react';
|
||||
|
||||
import MinusIcon from 'components/icons/minus';
|
||||
import PlusIcon from 'components/icons/plus';
|
||||
import type { CartItem } from 'lib/shopify/types';
|
||||
import LoadingDots from '../loading-dots';
|
||||
|
||||
export default function EditItemQuantityButton({
|
||||
item,
|
||||
type
|
||||
}: {
|
||||
item: CartItem;
|
||||
type: 'plus' | 'minus';
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [editing, setEditing] = useState(false);
|
||||
|
||||
async function handleEdit() {
|
||||
setEditing(true);
|
||||
|
||||
const response = await fetch(`/api/cart`, {
|
||||
method: type === 'minus' && item.quantity - 1 === 0 ? 'DELETE' : 'PUT',
|
||||
body: JSON.stringify({
|
||||
lineId: item.id,
|
||||
variantId: item.merchandise.id,
|
||||
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.error) {
|
||||
alert(data.error);
|
||||
return;
|
||||
}
|
||||
|
||||
setEditing(false);
|
||||
|
||||
startTransition(() => {
|
||||
router.refresh();
|
||||
});
|
||||
}
|
||||
return (
|
||||
<button
|
||||
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
|
||||
onClick={handleEdit}
|
||||
disabled={editing}
|
||||
className={`${editing ? 'cursor-not-allowed' : ''} ${
|
||||
type === 'minus' ? 'ml-auto' : ''
|
||||
} flex h-8 w-8 items-center justify-center border-l border-black/40 bg-black/0 hover:bg-black/10 dark:border-white/40 dark:bg-white/0 dark:hover:bg-white/10`}
|
||||
>
|
||||
{editing ? (
|
||||
<LoadingDots className="bg-white dark:bg-black" />
|
||||
) : type === 'plus' ? (
|
||||
<PlusIcon className="h-4" />
|
||||
) : (
|
||||
<MinusIcon className="h-4" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
23
components/cart/index.tsx
Normal file
23
components/cart/index.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { createCart, getCart } from 'lib/shopify';
|
||||
import { cookies } from 'next/headers';
|
||||
import CartButton from './button';
|
||||
|
||||
export default async function Cart() {
|
||||
const cartId = cookies().get('cartId')?.value;
|
||||
let cartIdUpdated = false;
|
||||
let cart;
|
||||
|
||||
if (cartId) {
|
||||
cart = await getCart(cartId);
|
||||
}
|
||||
|
||||
// If the `cartId` from the cookie is not set or the cart is empty
|
||||
// (old carts becomes `null` when you checkout), then get a new `cartId`
|
||||
// and re-fetch the cart.
|
||||
if (!cartId || !cart) {
|
||||
cart = await createCart();
|
||||
cartIdUpdated = true;
|
||||
}
|
||||
|
||||
return <CartButton cart={cart} cartIdUpdated={cartIdUpdated} />;
|
||||
}
|
174
components/cart/modal.tsx
Normal file
174
components/cart/modal.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import Image from 'next/image';
|
||||
|
||||
import CloseIcon from 'components/icons/close';
|
||||
import ShoppingBagIcon from 'components/icons/shopping-bag';
|
||||
import Price from 'components/price';
|
||||
import { DEFAULT_OPTION } from 'lib/constants';
|
||||
import type { Cart } from 'lib/shopify/types';
|
||||
import DeleteItemButton from './delete-item-button';
|
||||
import EditItemQuantityButton from './edit-item-quantity-button';
|
||||
|
||||
export default function CartModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
cart
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
cart: Cart;
|
||||
}) {
|
||||
return (
|
||||
<AnimatePresence initial={false}>
|
||||
{isOpen && (
|
||||
<Dialog
|
||||
as={motion.div}
|
||||
initial="closed"
|
||||
animate="open"
|
||||
exit="closed"
|
||||
key="dialog"
|
||||
static
|
||||
open={isOpen}
|
||||
onClose={onClose}
|
||||
className="relative z-50"
|
||||
>
|
||||
<motion.div
|
||||
variants={{
|
||||
open: { opacity: 1, backdropFilter: 'blur(0.5px)' },
|
||||
closed: { opacity: 0, backdropFilter: 'blur(0px)' }
|
||||
}}
|
||||
className="fixed inset-0 bg-black/30"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<div className="fixed inset-0 flex justify-end" data-testid="cart">
|
||||
<Dialog.Panel
|
||||
as={motion.div}
|
||||
variants={{
|
||||
open: { translateX: 0 },
|
||||
closed: { translateX: '100%' }
|
||||
}}
|
||||
transition={{ type: 'spring', bounce: 0, duration: 0.3 }}
|
||||
className="flex w-full flex-col bg-white p-8 text-black dark:bg-black dark:text-white md:w-1/3 lg:w-[30%] lg:px-6"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-lg font-bold">My Cart</p>
|
||||
<button
|
||||
aria-label="Close cart"
|
||||
onClick={onClose}
|
||||
className="text-black transition-colors hover:text-gray-500 dark:text-gray-100"
|
||||
data-testid="close-cart"
|
||||
>
|
||||
<CloseIcon className="h-7" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{cart.lines.length === 0 ? (
|
||||
<div className="mt-20 flex w-full flex-col items-center justify-center overflow-hidden">
|
||||
<ShoppingBagIcon className="h-16" />
|
||||
<p className="mt-6 text-center text-2xl font-bold">Your cart is empty.</p>
|
||||
</div>
|
||||
) : null}
|
||||
{cart.lines.length !== 0 ? (
|
||||
<div className="flex h-full flex-col justify-between overflow-hidden">
|
||||
<ul className="flex-grow overflow-auto p-6">
|
||||
{cart.lines.map((item, i) => {
|
||||
return (
|
||||
<li key={i} data-testid="cart-item">
|
||||
<div className="mb-2 flex w-full">
|
||||
<div className="relative h-20 w-20 flex-none">
|
||||
{item.merchandise.product.featuredImage.url && (
|
||||
<Image
|
||||
alt={
|
||||
item.merchandise.product.featuredImage.altText ||
|
||||
item.merchandise.product.title
|
||||
}
|
||||
className="bg-white"
|
||||
fill
|
||||
src={item.merchandise.product.featuredImage.url}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-4 flex w-full flex-col justify-between">
|
||||
<div className="flex w-full justify-between">
|
||||
<div>
|
||||
<p
|
||||
className="text-lg font-medium"
|
||||
data-testid="cart-product-name"
|
||||
>
|
||||
{item.merchandise.product.title}
|
||||
</p>
|
||||
{item.merchandise.title !== DEFAULT_OPTION ? (
|
||||
<p className="text-sm" data-testid="cart-product-variant">
|
||||
{item.merchandise.title}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Price
|
||||
className="font-medium"
|
||||
amount={item.cost.totalAmount.amount}
|
||||
currencyCode={item.cost.totalAmount.currencyCode}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-4 flex w-full">
|
||||
<DeleteItemButton item={item} />
|
||||
<div className="flex h-8 w-full border border-black/40 dark:border-white/40">
|
||||
<div className="flex h-full items-center px-2 ">{item.quantity}</div>
|
||||
<EditItemQuantityButton item={item} type="minus" />
|
||||
<EditItemQuantityButton item={item} type="plus" />
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<div className="border-t border-white/60 p-6">
|
||||
<div className="text-sm text-white">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<p>Subtotal</p>
|
||||
<Price
|
||||
className="text-right"
|
||||
amount={cart.cost.subtotalAmount.amount}
|
||||
currencyCode={cart.cost.subtotalAmount.currencyCode}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<p>Taxes</p>
|
||||
<Price
|
||||
className="text-right"
|
||||
amount={cart.cost.totalTaxAmount.amount}
|
||||
currencyCode={cart.cost.totalTaxAmount.currencyCode}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-2 flex items-center justify-between border-b border-white/30 pb-2">
|
||||
<p>Shipping</p>
|
||||
<p className="text-right uppercase">calculated at checkout</p>
|
||||
</div>
|
||||
<div className="mb-2 flex items-center justify-between font-bold">
|
||||
<p>Total</p>
|
||||
<Price
|
||||
className="text-right"
|
||||
amount={cart.cost.totalAmount.amount}
|
||||
currencyCode={cart.cost.totalAmount.currencyCode}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
href={cart.checkoutUrl}
|
||||
className="mt-6 flex w-full items-center justify-center bg-black p-3 text-sm font-medium uppercase text-white opacity-90 hover:opacity-100 dark:bg-white dark:text-black"
|
||||
>
|
||||
<span>Proceed to Checkout</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
Reference in New Issue
Block a user