Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(storefront): instant cart drawer, optimistic cart edits and faster page loads (#1711)

Viktor Holik08a03e913b75
diff --git a/apps/storefront/src/app/[locale]/(main)/layout.tsx b/apps/storefront/src/app/[locale]/(main)/layout.tsx
index a7ed14f6e..4d909f938 100644
--- a/apps/storefront/src/app/[locale]/(main)/layout.tsx
+++ b/apps/storefront/src/app/[locale]/(main)/layout.tsx
@@ -15,8 +15,7 @@ export default async function RootLayout({
const APP_ID = process.env.NEXT_PUBLIC_TALKJS_APP_ID;
const { locale } = await params;
- const user = await retrieveCustomer();
- const regionCheck = await checkRegion(locale);
+ const [user, regionCheck] = await Promise.all([retrieveCustomer(), checkRegion(locale)]);
if (!regionCheck) {
return redirect('/');
diff --git a/apps/storefront/src/app/[locale]/(main)/products/[handle]/page.tsx b/apps/storefront/src/app/[locale]/(main)/products/[handle]/page.tsx
index 253a38a3b..a6f5c0115 100644
--- a/apps/storefront/src/app/[locale]/(main)/products/[handle]/page.tsx
+++ b/apps/storefront/src/app/[locale]/(main)/products/[handle]/page.tsx
@@ -1,4 +1,7 @@
+import { Suspense } from "react"
+
import { ProductDetailsPage } from "@/components/sections"
+import { ProductDetailsPageSkeleton } from "@/components/sections/ProductDetailsPage/ProductDetailsPage"
import { listProducts } from "@/lib/data/products"
import { generateProductMetadata } from "@/lib/helpers/seo"
import type { Metadata } from "next"
@@ -27,7 +30,9 @@ export default async function ProductPage({
return (
<main className="container">
- <ProductDetailsPage handle={handle} locale={locale} />
+ <Suspense key={handle} fallback={<ProductDetailsPageSkeleton />}>
+ <ProductDetailsPage handle={handle} locale={locale} />
+ </Suspense>
</main>
)
}
diff --git a/apps/storefront/src/app/[locale]/(main)/sellers/[handle]/page.tsx b/apps/storefront/src/app/[locale]/(main)/sellers/[handle]/page.tsx
index f18d583ab..2d8082934 100644
--- a/apps/storefront/src/app/[locale]/(main)/sellers/[handle]/page.tsx
+++ b/apps/storefront/src/app/[locale]/(main)/sellers/[handle]/page.tsx
@@ -75,9 +75,10 @@ export default async function SellerPage({
const { handle, locale } = await params
const { page } = await searchParams
- const seller = (await getSellerByHandle(handle)) as SellerDTO
-
- const user = await retrieveCustomer()
+ const [seller, user] = (await Promise.all([
+ getSellerByHandle(handle),
+ retrieveCustomer(),
+ ])) as [SellerDTO, Awaited<ReturnType<typeof retrieveCustomer>>]
const tab = "offers"
diff --git a/apps/storefront/src/app/layout.tsx b/apps/storefront/src/app/layout.tsx
index 3758cc74d..7a590b256 100644
--- a/apps/storefront/src/app/layout.tsx
+++ b/apps/storefront/src/app/layout.tsx
@@ -22,12 +22,12 @@ export const metadata: Metadata = {
metadataBase: new URL(process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000')
};
-export default async function RootLayout({
+export default function RootLayout({
children
}: Readonly<{
children: React.ReactNode;
}>) {
- const cart = await retrieveCart();
+ const cartPromise = retrieveCart();
// default lang updated by HtmlLangSetter
const htmlLang = 'en';
@@ -87,7 +87,7 @@ export default async function RootLayout({
</Head>
<body className="relative bg-primary text-secondary antialiased">
<HtmlLangSetter />
- <Providers cart={cart}>{children}</Providers>
+ <Providers cartPromise={cartPromise}>{children}</Providers>
<Toaster position="top-right" />
</body>
</html>
diff --git a/apps/storefront/src/app/providers.tsx b/apps/storefront/src/app/providers.tsx
index 885f8d6c8..beac944df 100644
--- a/apps/storefront/src/app/providers.tsx
+++ b/apps/storefront/src/app/providers.tsx
@@ -1,5 +1,6 @@
"use client"
+import { CartDrawer } from "@/components/cells/CartDrawer/CartDrawer"
import { CartProvider } from "@/components/providers"
import { Cart } from "@/types/cart"
import type React from "react"
@@ -7,9 +8,14 @@ import type React from "react"
import { PropsWithChildren } from "react"
interface ProvidersProps extends PropsWithChildren {
- cart: Cart | null
+ cartPromise: Promise<Cart | null>
}
-export function Providers({ children, cart }: ProvidersProps) {
- return <CartProvider cart={cart}>{children}</CartProvider>
+export function Providers({ children, cartPromise }: ProvidersProps) {
+ return (
+ <CartProvider cartPromise={cartPromise}>
+ {children}
+ <CartDrawer />
+ </CartProvider>
+ )
}
diff --git a/apps/storefront/src/components/cells/CartButton/CartButton.tsx b/apps/storefront/src/components/cells/CartButton/CartButton.tsx
new file mode 100644
index 000000000..61dd1747b
--- /dev/null
+++ b/apps/storefront/src/components/cells/CartButton/CartButton.tsx
@@ -0,0 +1,30 @@
+"use client"
+
+import { Badge } from "@/components/atoms"
+import { useCartContext } from "@/components/providers"
+import { useCartDrawer } from "@/components/providers/Cart/drawer"
+import { CartIcon } from "@/icons"
+
+export const CartButton = () => {
+ const { cart } = useCartContext()
+ const { openDrawer } = useCartDrawer()
+
+ const count = cart?.items?.reduce((acc, item) => acc + item.quantity, 0) || 0
+
+ return (
+ <button
+ type="button"
+ onClick={openDrawer}
+ className="relative flex cursor-pointer items-center justify-center"
+ aria-label="Open cart"
+ data-testid="header-cart-button"
+ >
+ <CartIcon size={20} />
+ {count > 0 && (
+ <Badge className="absolute -top-2 -right-2 w-4 h-4 p-0" data-testid="header-cart-count">
+ {count}
+ </Badge>
+ )}
+ </button>
+ )
+}
diff --git a/apps/storefront/src/components/cells/CartDrawer/CartDrawer.tsx b/apps/storefront/src/components/cells/CartDrawer/CartDrawer.tsx
new file mode 100644
index 000000000..639c987b3
--- /dev/null
+++ b/apps/storefront/src/components/cells/CartDrawer/CartDrawer.tsx
@@ -0,0 +1,232 @@
+"use client"
+
+import { Suspense } from "react"
+import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from "@headlessui/react"
+import { HttpTypes } from "@medusajs/types"
+import Image from "next/image"
+
+import { Button } from "@/components/atoms"
+import LocalizedClientLink from "@/components/molecules/LocalizedLink/LocalizedLink"
+import { DeleteCartItemButton } from "@/components/molecules/DeleteCartItemButton/DeleteCartItemButton"
+import { UpdateCartItemButton } from "@/components/molecules/UpdateCartItemButton/UpdateCartItemButton"
+import { useCartContext } from "@/components/providers"
+import { useCartDrawer } from "@/components/providers/Cart/drawer"
+import { CloseIcon } from "@/icons"
+import Spinner from "@/icons/spinner"
+import { filterValidCartItems } from "@/lib/helpers/filter-valid-cart-items"
+import { convertToLocale } from "@/lib/helpers/money"
+
+type CartLine = HttpTypes.StoreCartLineItem & {
+ offer?: { seller?: { name?: string } | null } | null
+}
+
+export const CartDrawer = () => {
+ const { closeDrawer, isDrawerOpen } = useCartDrawer()
+
+ return (
+ <Dialog open={isDrawerOpen} onClose={closeDrawer} className="relative z-50">
+ <DialogBackdrop
+ transition
+ className="fixed inset-0 bg-black/20 transition-opacity duration-200 ease-out data-[closed]:opacity-0"
+ />
+ <div className="fixed inset-y-0 right-0 flex w-full max-w-md">
+ <DialogPanel
+ transition
+ className="flex h-full w-full flex-col bg-primary shadow-lg transition-transform duration-300 ease-out data-[closed]:translate-x-full"
+ data-testid="cart-drawer"
+ >
+ <div className="flex items-center justify-between border-b px-4 py-4">
+ <DialogTitle className="heading-md uppercase">Cart</DialogTitle>
+ <button
+ type="button"
+ onClick={closeDrawer}
+ aria-label="Close cart"
+ className="flex h-8 w-8 cursor-pointer items-center justify-center"
+ data-testid="cart-drawer-close"
+ >
+ <CloseIcon size={20} />
+ </button>
+ </div>
+ <Suspense
+ fallback={
+ <div
+ aria-busy="true"
+ className="flex flex-1 items-center justify-center gap-2 label-md text-secondary"
+ role="status"
+ >
+ <Spinner /> Loading cart…
+ </div>
+ }
+ >
+ <CartDrawerContent />
+ </Suspense>
+ </DialogPanel>
+ </div>
+ </Dialog>
+ )
+}
+
+const CartDrawerContent = () => {
+ const { cart, isUpdating } = useCartContext()
+ const { closeDrawer } = useCartDrawer()
+
+ const items = filterValidCartItems(cart?.items) as CartLine[]
+ const currencyCode = cart?.currency_code || "eur"
+
+ if (!items.length) {
+ return (
+ <div
+ className="flex flex-1 flex-col items-center justify-center gap-6 px-8 text-center"
+ data-testid="cart-drawer-empty"
+ >
+ <h3 className="heading-md uppercase">Your cart is empty</h3>
+ <LocalizedClientLink href="/categories" onClick={closeDrawer}>
+ <Button className="px-8 py-3" data-testid="cart-drawer-continue-shopping">
+ Continue shopping
+ </Button>
+ </LocalizedClientLink>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <ul
+ className="flex flex-1 flex-col gap-4 overflow-y-auto px-4 py-4"
+ data-testid="cart-drawer-items"
+ >
+ {items.map((item) => (
+ <CartDrawerLine
+ key={item.id}
+ item={item}
+ currencyCode={currencyCode}
+ onNavigate={closeDrawer}
+ />
+ ))}
+ </ul>
+ <footer className="flex flex-col gap-4 border-t px-4 py-4">
+ <div aria-busy={isUpdating || undefined} className="flex flex-col gap-1">
+ <div className="flex items-baseline justify-between">
+ <span className="label-lg">Subtotal</span>
+ {isUpdating ? (
+ <span className="label-lg text-secondary" data-testid="cart-drawer-total-updating">
+ Updating…
+ </span>
+ ) : (
+ <span className="heading-sm" data-testid="cart-drawer-total">
+ {convertToLocale({
+ amount: cart?.item_subtotal || 0,
+ currency_code: currencyCode,
+ })}
+ </span>
+ )}
+ </div>
+ <p className="label-sm text-secondary">
+ Taxes and shipping calculated at checkout.
+ </p>
+ </div>
+ {isUpdating ? (
+ <Button className="w-full py-3" disabled data-testid="cart-drawer-checkout">
+ Go to checkout
+ </Button>
+ ) : (
+ <LocalizedClientLink href="/checkout?step=address" onClick={closeDrawer}>
+ <Button className="w-full py-3" data-testid="cart-drawer-checkout">
+ Go to checkout
+ </Button>
+ </LocalizedClientLink>
+ )}
+ <LocalizedClientLink
+ href="/cart"
+ onClick={closeDrawer}
+ className="label-md text-center underline"
+ data-testid="cart-drawer-view-cart"
+ >
+ View cart
+ </LocalizedClientLink>
+ </footer>
+ </div>
+ )
+}
+
+const CartDrawerLine = ({
+ item,
+ currencyCode,
+ onNavigate,
+}: {
+ item: CartLine
+ currencyCode: string
+ onNavigate: () => void
+}) => {
+ const { isLinePending } = useCartContext()
+ const isPending = isLinePending(item)
+ const href = item.product_handle ? `/products/${item.product_handle}` : undefined
+ const options = Object.entries(item.variant_option_values ?? {})
+ const sellerName = item.offer?.seller?.name
+
+ const thumbnail = item.thumbnail ? (
+ <Image
+ src={decodeURIComponent(item.thumbnail)}
+ alt={item.product_title || "Product"}
+ fill
+ sizes="80px"
+ className="object-cover"
+ />
+ ) : (
+ <Image
+ src="/images/placeholder.svg"
+ alt=""
+ fill
+ sizes="80px"
+ className="object-contain p-4 opacity-30"
+ />
+ )
+
+ return (
+ <li
+ className="flex gap-3"
+ aria-busy={isPending || undefined}
+ data-testid="cart-drawer-item"
+ >
+ {href ? (
+ <LocalizedClientLink
+ href={href}
+ onClick={onNavigate}
+ className="relative h-24 w-20 shrink-0 overflow-hidden rounded-xs border"
+ >
+ {thumbnail}
+ </LocalizedClientLink>
+ ) : (
+ <div className="relative h-24 w-20 shrink-0 overflow-hidden rounded-xs border">
+ {thumbnail}
+ </div>
+ )}
+ <div className="flex min-w-0 flex-1 flex-col justify-between gap-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <h3 className="heading-xs truncate uppercase">{item.product_title}</h3>
+ <div className="label-sm text-secondary">
+ {options.map(([title, value]) => (
+ <p key={title}>
+ {title}: <span className="text-primary">{String(value)}</span>
+ </p>
+ ))}
+ {sellerName && <p>Sold by {sellerName}</p>}
+ </div>
+ </div>
+ <span
+ className="label-lg shrink-0 tabular-nums data-[pending=true]:text-secondary"
+ data-pending={isPending}
+ data-testid="cart-drawer-item-price"
+ >
+ {convertToLocale({ amount: item.subtotal ?? 0, currency_code: currencyCode })}
+ </span>
+ </div>
+ <div className="flex items-center justify-between">
+ <UpdateCartItemButton quantity={item.quantity} lineItemId={item.id} compact />
+ <DeleteCartItemButton id={item.id} />
+ </div>
+ </div>
+ </li>
+ )
+}
diff --git a/apps/storefront/src/components/cells/CartDropdown/CartDropdown.tsx b/apps/storefront/src/components/cells/CartDropdown/CartDropdown.tsx
deleted file mode 100644
index 40eb9cdaf..000000000
--- a/apps/storefront/src/components/cells/CartDropdown/CartDropdown.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-"use client"
-
-import { Badge, Button } from "@/components/atoms"
-import { CartDropdownItem, Dropdown } from "@/components/molecules"
-import { usePrevious } from "@/hooks/usePrevious"
-import LocalizedClientLink from "@/components/molecules/LocalizedLink/LocalizedLink"
-import { CartIcon } from "@/icons"
-import { convertToLocale } from "@/lib/helpers/money"
-import { filterValidCartItems } from "@/lib/helpers/filter-valid-cart-items"
-import { HttpTypes } from "@medusajs/types"
-import { useEffect, useState } from "react"
-import { usePathname } from "next/navigation"
-import { useCartContext } from "@/components/providers"
-
-const getItemCount = (cart: HttpTypes.StoreCart | null) => {
- return cart?.items?.reduce((acc, item) => acc + item.quantity, 0) || 0
-}
-
-export const CartDropdown = () => {
- const { cart } = useCartContext()
- const [open, setOpen] = useState(false)
-
- const previousItemCount = usePrevious(getItemCount(cart))
- const cartItemsCount = (cart && getItemCount(cart)) || 0
- const pathname = usePathname()
-
- const validItems = filterValidCartItems(cart?.items)
-
- const total = convertToLocale({
- amount: cart?.total || 0,
- currency_code: cart?.currency_code || "eur",
- })
-
- const delivery = convertToLocale({
- amount: cart?.shipping_subtotal || 0,
- currency_code: cart?.currency_code || "eur",
- })
-
- const tax = convertToLocale({
- amount: cart?.tax_total || 0,
- currency_code: cart?.currency_code || "eur",
- })
-
- const items = convertToLocale({
- amount: cart?.item_subtotal || 0,
- currency_code: cart?.currency_code || "eur",
- })
-
- useEffect(() => {
- if (open) {
- const timeout = setTimeout(() => {
- setOpen(false)
- }, 2000)
-
- return () => clearTimeout(timeout)
- }
- }, [open])
-
- useEffect(() => {
- if (
- previousItemCount !== undefined &&
- cartItemsCount > previousItemCount &&
- pathname.split("/")[2] !== "cart"
- ) {
- setOpen(true)
- }
- }, [cartItemsCount, previousItemCount])
-
- return (
- <div
- className="relative"
- onMouseOver={() => setOpen(true)}
- onMouseLeave={() => setOpen(false)}
- >
- <LocalizedClientLink
- href="/cart"
- className="relative"
- aria-label="Go to cart"
- >
- <CartIcon size={20} />
- {Boolean(cartItemsCount) && (
- <Badge className="absolute -top-2 -right-2 w-4 h-4 p-0">
- {cartItemsCount}
- </Badge>
- )}
- </LocalizedClientLink>
- <Dropdown show={open}>
- <div className="lg:w-[460px] shadow-lg">
- <h3 className="uppercase heading-md border-b p-4">Shopping cart</h3>
- <div className="p-4">
- {Boolean(cartItemsCount) ? (
- <div>
- <div className="overflow-y-scroll max-h-[360px] no-scrollbar">
- {validItems.map((item, index) => (
- <CartDropdownItem
- key={item.id ?? index}
- item={item}
- currency_code={cart?.currency_code || "eur"}
- />
- ))}
- </div>
- <div className="pt-4">
- <div className="text-secondary flex justify-between items-center">
- Items <p className="label-md text-primary">{items}</p>
- </div>
- <div className="text-secondary flex justify-between items-center">
- Delivery <p className="label-md text-primary">{delivery}</p>
- </div>
- <div className="text-secondary flex justify-between items-center">
- Tax <p className="label-md text-primary">{tax}</p>
- </div>
- <div className="text-secondary flex justify-between items-center">
- Total <p className="label-xl text-primary">{total}</p>
- </div>
- <LocalizedClientLink href="/cart">
- <Button className="w-full mt-4 py-3">Go to cart</Button>
- </LocalizedClientLink>
- </div>
- </div>
- ) : (
- <div className="px-8">
- <h4 className="heading-md uppercase text-center">
- Your shopping cart is empty
- </h4>
- <p className="text-lg text-center py-4">
- Are you looging for inspiration?
- </p>
- <LocalizedClientLink href="/categories">
- <Button className="w-full py-3">Explore Home Page</Button>
- </LocalizedClientLink>
- </div>
- )}
- </div>
- </div>
- </Dropdown>
- </div>
- )
-}
diff --git a/apps/storefront/src/components/cells/ProductDetailsHeader/ProductDetailsHeader.tsx b/apps/storefront/src/components/cells/ProductDetailsHeader/ProductDetailsHeader.tsx
index 8fcac2dc8..f628e3ffd 100644
--- a/apps/storefront/src/components/cells/ProductDetailsHeader/ProductDetailsHeader.tsx
+++ b/apps/storefront/src/components/cells/ProductDetailsHeader/ProductDetailsHeader.tsx
@@ -19,6 +19,8 @@ import { CompareOffersModal } from "@/components/organisms/CompareOffersModal/Co
import { SellerDTO } from "@mercurjs/types"
import { toast } from "@/lib/helpers/toast"
import { useCartContext } from "@/components/providers"
+import { useCartDrawer } from "@/components/providers/Cart/drawer"
+import { MinusThinIcon, PlusIcon } from "@/icons"
const optionsAsKeymap = (
variantOptions: HttpTypes.StoreProductVariant["options"]
@@ -49,9 +51,11 @@ export const ProductDetailsHeader = ({
offers?: StoreOffer[]
seller?: SellerDTO
}) => {
- const { addToCart, onAddToCart, cart, isAddingItem } = useCartContext()
+ const { addToCart, cart, isAddingItem } = useCartContext()
const { allSearchParams } = useGetAllSearchParams()
+ const { openDrawer } = useCartDrawer()
const [isCompareOpen, setIsCompareOpen] = useState(false)
+ const [quantity, setQuantity] = useState(1)
const { cheapestVariant, cheapestPrice } = getProductPrice({
product,
@@ -107,6 +111,9 @@ export const ProductDetailsHeader = ({
const isAddToCartDisabled =
!hasOffer || !offerStock || isStockMaxLimitReached
+ const maxQuantity = Math.max(1, Math.min(99, offerStock - quantityInCart))
+ const selectedQuantity = Math.min(quantity, maxQuantity)
+
const handleAddToCart = async () => {
if (!winnerOffer || isAddToCartDisabled) return
@@ -117,23 +124,25 @@ export const ProductDetailsHeader = ({
const storeCartLineItem = {
thumbnail: product.thumbnail || "",
product_title: product.title,
- quantity: 1,
- subtotal,
- total,
- tax_total: total - subtotal,
+ quantity: selectedQuantity,
+ subtotal: subtotal * selectedQuantity,
+ total: total * selectedQuantity,
+ tax_total: (total - subtotal) * selectedQuantity,
variant_id: variantId,
product_id: product.id,
variant: product.variants?.find(({ id }) => id === variantId),
metadata: { offer_id: winnerOffer.id },
}
- onAddToCart(storeCartLineItem, offerCurrency)
+ openDrawer()
+ setQuantity(1)
try {
await addToCart({
offerId: winnerOffer.id,
- quantity: 1,
+ quantity: selectedQuantity,
countryCode: locale,
+ optimisticItem: { item: storeCartLineItem, currencyCode: offerCurrency },
})
} catch (error) {
toast.error({
@@ -168,11 +177,47 @@ export const ProductDetailsHeader = ({
{hasAnyPrice && (
<ProductVariants product={product} selectedVariant={selectedVariant} />
)}
+ <div className="mb-4 flex gap-2">
+ <div
+ aria-label="Item quantity"
+ role="group"
+ className="flex shrink-0 items-center rounded-sm border"
+ data-testid="product-quantity-picker"
+ >
+ <button
+ type="button"
+ aria-label="Decrease quantity"
+ className="flex h-full w-10 cursor-pointer items-center justify-center disabled:cursor-not-allowed disabled:opacity-40"
+ disabled={isAddToCartDisabled || selectedQuantity <= 1}
+ onClick={() => setQuantity(Math.max(1, selectedQuantity - 1))}
+ data-testid="product-quantity-decrease"
+ >
+ <MinusThinIcon size={16} />
+ </button>
+ <span
+ aria-live="polite"
+ role="status"
+ className="label-md w-8 text-center tabular-nums"
+ data-testid="product-quantity-value"
+ >
+ {selectedQuantity}
+ </span>
+ <button
+ type="button"
+ aria-label="Increase quantity"
+ className="flex h-full w-10 cursor-pointer items-center justify-center disabled:cursor-not-allowed disabled:opacity-40"
+ disabled={isAddToCartDisabled || selectedQuantity >= maxQuantity}
+ onClick={() => setQuantity(Math.min(maxQuantity, selectedQuantity + 1))}
+ data-testid="product-quantity-increase"
+ >
+ <PlusIcon size={16} />
+ </button>
+ </div>
<Button
onClick={handleAddToCart}
disabled={isAddToCartDisabled}
loading={isAddingItem}
- className="w-full uppercase mb-4 py-3 flex justify-center"
+ className="w-full uppercase py-3 flex justify-center"
size="large"
data-testid="product-add-to-cart-button"
>
@@ -182,6 +227,7 @@ export const ProductDetailsHeader = ({
? "ADD TO CART"
: "OUT OF STOCK"}
</Button>
+ </div>
{otherOffersCount > 0 && (
<Button
variant="tonal"
diff --git a/apps/storefront/src/components/cells/index.ts b/apps/storefront/src/components/cells/index.ts
index 802307742..e4a61aa5a 100644
--- a/apps/storefront/src/components/cells/index.ts
+++ b/apps/storefront/src/components/cells/index.ts
@@ -1,7 +1,7 @@
import { ActiveFilterElement } from './ActiveFilterElement/ActiveFilterElement';
import { BrandFilter } from './BrandFilter/BrandFilter';
import { CustomCarousel as Carousel } from './Carousel/Carousel';
-import { CartDropdown } from './CartDropdown/CartDropdown';
+import { CartButton } from './CartButton/CartButton';
import { CartItemsFooter } from './CartItemsFooter/CartItemsFooter';
import { CartItemsHeader } from './CartItemsHeader/CartItemsHeader';
import { CartItemsProducts } from './CartItemsProducts/CartItemsProducts';
@@ -54,7 +54,7 @@ export {
CartItemsFooter,
CartItemsProducts,
HeadingCategories,
- CartDropdown,
+ CartButton,
LabeledInput,
OrderAddresses,
OrderProductListItem,
diff --git a/apps/storefront/src/components/molecules/CartDropdownItem/CartDropdownItem.tsx b/apps/storefront/src/components/molecules/CartDropdownItem/CartDropdownItem.tsx
deleted file mode 100644
index b8c95c917..000000000
--- a/apps/storefront/src/components/molecules/CartDropdownItem/CartDropdownItem.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { convertToLocale } from "@/lib/helpers/money"
-import { HttpTypes } from "@medusajs/types"
-import Image from "next/image"
-
-export const CartDropdownItem = ({
- item,
- currency_code,
-}: {
- item: HttpTypes.StoreCartLineItem
- currency_code: string
-}) => {
- const original_total = convertToLocale({
- amount: (item.compare_at_unit_price || 0) * item.quantity,
- currency_code,
- })
-
- const total = convertToLocale({
- amount: item.subtotal ?? 0,
- currency_code,
- })
-
- return (
- <div className="border rounded-sm p-1 flex gap-2 mb-4">
- <div className="w-[100px] h-[132px] flex items-center justify-center">
- {item.thumbnail ? (
- <Image
- src={decodeURIComponent(item.thumbnail)}
- alt={item.product_title || ""}
- width={80}
- height={90}
- className="w-[80px] h-[90px] object-cover rounded-xs"
- priority
- />
- ) : (
- <Image
- src={"/images/placeholder.svg"}
- alt="Product thumbnail"
- width={50}
- height={66}
- className="rounded-xs w-[50px] h-[66px] object-contain opacity-30"
- />
- )}
- </div>
-
- <div className="py-2">
- <h4 className="heading-xs">{item.product_title}</h4>
- <div className="label-md text-secondary">
- {Object.entries(item.variant_option_values ?? {}).map(([title, value]) => (
- <p key={title}>
- {title}: <span className="text-primary">{String(value)}</span>
- </p>
- ))}
- <p>
- Quantity: <span className="text-primary">{item.quantity}</span>
- </p>
- </div>
- <div className="pt-2 flex items-center gap-2 mt-4 lg:mt-0">
- <p className="label-lg">{total}</p>
- </div>
- </div>
- </div>
- )
-}
diff --git a/apps/storefront/src/components/molecules/DeleteCartItemButton/DeleteCartItemButton.tsx b/apps/storefront/src/components/molecules/DeleteCartItemButton/DeleteCartItemButton.tsx
index 946736f7f..20527416c 100644
--- a/apps/storefront/src/components/molecules/DeleteCartItemButton/DeleteCartItemButton.tsx
+++ b/apps/storefront/src/components/molecules/DeleteCartItemButton/DeleteCartItemButton.tsx
@@ -12,7 +12,7 @@ export const DeleteCartItemButton = ({
id: string
disabled?: boolean
}) => {
- const { removeCartItem, isRemovingItem } = useCartContext()
+ const { removeCartItem } = useCartContext()
const handleDelete = async (id: string) => {
try {
@@ -25,16 +25,16 @@ export const DeleteCartItemButton = ({
}
}
- const isBtnDisabled = isRemovingItem || disabled || !id
+ const isBtnDisabled = disabled || !id || id.startsWith("optimistic:")
return (
<Button
variant="text"
- className="w-10 h-10 flex items-center justify-center p-0"
+ className="w-10 h-10 flex items-center justify-center p-0 disabled:bg-transparent disabled:opacity-40"
onClick={() => handleDelete(id)}
- loading={isRemovingItem}
disabled={isBtnDisabled}
aria-label="Remove item from cart"
+ data-testid="cart-item-remove"
>
<BinIcon size={20} />
</Button>
diff --git a/apps/storefront/src/components/molecules/UpdateCartItemButton/UpdateCartItemButton.tsx b/apps/storefront/src/components/molecules/UpdateCartItemButton/UpdateCartItemButton.tsx
index 982341051..1a181a52e 100644
--- a/apps/storefront/src/components/molecules/UpdateCartItemButton/UpdateCartItemButton.tsx
+++ b/apps/storefront/src/components/molecules/UpdateCartItemButton/UpdateCartItemButton.tsx
@@ -1,94 +1,81 @@
'use client';
-import { useEffect, useRef, useState } from 'react';
-
-import { useRouter } from 'next/navigation';
-
-import { Button } from '@/components/atoms';
import { useCartContext } from '@/components/providers';
+import { MinusThinIcon, PlusIcon } from '@/icons';
+import { cn } from '@/lib/utils';
import { toast } from '@/lib/helpers/toast';
+const MAX_QUANTITY = 99;
+
export const UpdateCartItemButton = ({
quantity,
- lineItemId
+ lineItemId,
+ compact = false
}: {
quantity: number;
lineItemId: string;
+ compact?: boolean;
}) => {
- const { updateCartItem, isUpdatingItem } = useCartContext();
- const [pendingQuantity, setPendingQuantity] = useState(quantity);
- const debounceTimerRef = useRef<NodeJS.Timeout>(null);
- const router = useRouter();
-
- useEffect(() => {
- setPendingQuantity(quantity);
- }, [quantity]);
+ const { updateCartItem } = useCartContext();
+ const isOptimisticLine = !lineItemId || lineItemId.startsWith('optimistic:');
- useEffect(() => {
- return () => {
- if (debounceTimerRef.current) {
- clearTimeout(debounceTimerRef.current);
- }
- };
- }, []);
+ const handleQuantityChange = async (newQuantity: number) => {
+ if (newQuantity < 1 || newQuantity > MAX_QUANTITY) return;
- const handleQuantityChange = (newQuantity: number) => {
- if (newQuantity < 1) return;
-
- setPendingQuantity(newQuantity);
-
- if (debounceTimerRef.current) {
- clearTimeout(debounceTimerRef.current);
+ try {
+ await updateCartItem(lineItemId, newQuantity);
+ } catch (error: unknown) {
+ const errorMessage =
+ error instanceof Error
+ ? error.message.replace('Error setting up the request: ', '')
+ : 'Failed to update quantity';
+ toast.error({
+ title: 'Error updating cart',
+ description: errorMessage
+ });
}
-
- debounceTimerRef.current = setTimeout(async () => {
- try {
- await updateCartItem(lineItemId, newQuantity);
- router.refresh();
- } catch (error: unknown) {
- setPendingQuantity(quantity);
- const errorMessage =
- error instanceof Error
- ? error.message.replace('Error setting up the request: ', '')
- : 'Failed to update quantity';
- toast.error({
- title: 'Error updating cart',
- description: errorMessage
- });
- }
- }, 500);
};
- const isDecreaseDisabled = pendingQuantity === 1 || isUpdatingItem || !lineItemId;
- const isIncreaseDisabled = isUpdatingItem || !lineItemId;
+ const buttonClassName = cn(
+ 'flex cursor-pointer items-center justify-center disabled:cursor-not-allowed disabled:opacity-40',
+ compact ? 'h-7 w-7' : 'h-8 w-8'
+ );
return (
- <div className="mt-2 flex items-center gap-4">
- <Button
- variant="tonal"
- className="flex h-8 w-8 items-center justify-center"
- disabled={isDecreaseDisabled}
- onClick={() => handleQuantityChange(pendingQuantity - 1)}
+ <div
+ aria-label="Item quantity"
+ role="group"
+ className={cn('inline-flex items-center rounded-sm border', !compact && 'mt-2')}
+ data-testid="cart-item-quantity"
+ >
+ <button
+ type="button"
+ aria-label="Decrease quantity"
+ className={buttonClassName}
+ disabled={isOptimisticLine || quantity <= 1}
+ onClick={() => handleQuantityChange(quantity - 1)}
+ data-testid="cart-item-quantity-decrease"
>
- -
- </Button>
+ <MinusThinIcon size={compact ? 14 : 16} />
+ </button>
<span
- className={`font-medium transition-all duration-300 ${
- isDecreaseDisabled || isIncreaseDisabled
- ? 'scale-95 text-secondary opacity-70'
- : 'scale-100 text-primary opacity-100'
- }`}
+ aria-live="polite"
+ role="status"
+ className={cn('label-md text-center tabular-nums text-primary', compact ? 'w-6' : 'w-8')}
+ data-testid="cart-item-quantity-value"
>
- {pendingQuantity}
+ {quantity}
</span>
- <Button
- variant="tonal"
- className="flex h-8 w-8 items-center justify-center"
- disabled={isIncreaseDisabled}
- onClick={() => handleQuantityChange(pendingQuantity + 1)}
+ <button
+ type="button"
+ aria-label="Increase quantity"
+ className={buttonClassName}
+ disabled={isOptimisticLine || quantity >= MAX_QUANTITY}
+ onClick={() => handleQuantityChange(quantity + 1)}
+ data-testid="cart-item-quantity-increase"
>
- +
- </Button>
+ <PlusIcon size={compact ? 14 : 16} />
+ </button>
</div>
);
};
diff --git a/apps/storefront/src/components/molecules/index.ts b/apps/storefront/src/components/molecules/index.ts
index b9f059ea5..62fe471a9 100644
--- a/apps/storefront/src/components/molecules/index.ts
+++ b/apps/storefront/src/components/molecules/index.ts
@@ -1,6 +1,5 @@
import { Accordion } from './Accordion/Accordion';
import { AddressForm } from './AddressForm/AddressForm';
-import { CartDropdownItem } from './CartDropdownItem/CartDropdownItem';
import { CategoryNavbar } from './CategoryNavbar/CategoryNavbar';
import { DeleteCartItemButton } from './DeleteCartItemButton/DeleteCartItemButton';
import { Dropdown } from './Dropdown/Dropdown';
@@ -66,7 +65,6 @@ export {
HeaderCategoryNavbar,
DeleteCartItemButton,
Dropdown,
- CartDropdownItem,
LoginForm,
RegisterForm,
UserNavigation,
diff --git a/apps/storefront/src/components/organisms/CompareOffersModal/CompareOffersModal.tsx b/apps/storefront/src/components/organisms/CompareOffersModal/CompareOffersModal.tsx
index 608688532..25e063ae5 100644
--- a/apps/storefront/src/components/organisms/CompareOffersModal/CompareOffersModal.tsx
+++ b/apps/storefront/src/components/organisms/CompareOffersModal/CompareOffersModal.tsx
@@ -1,11 +1,10 @@
"use client"
-import { useState } from "react"
-
import { Badge, Button } from "@/components/atoms"
import { SellerAvatar } from "@/components/cells/SellerAvatar/SellerAvatar"
import { Modal } from "@/components/molecules/Modal/Modal"
import { useCartContext } from "@/components/providers"
+import { useCartDrawer } from "@/components/providers/Cart/drawer"
import { convertToLocale } from "@/lib/helpers/money"
import { toast } from "@/lib/helpers/toast"
import {
@@ -28,22 +27,42 @@ export const CompareOffersModal = ({
onClose: () => void
}) => {
const { addToCart } = useCartContext()
- const [addingId, setAddingId] = useState<string | null>(null)
+ const { openDrawer } = useCartDrawer()
const ranked = rankOffers(offers)
const handleAdd = async (offer: StoreOffer) => {
- setAddingId(offer.id)
+ const total = getOfferAmount(offer) ?? 0
+ const subtotal = offer.calculated_price?.calculated_amount_without_tax ?? total
+
+ onClose()
+ openDrawer()
+
try {
- await addToCart({ offerId: offer.id, quantity: 1, countryCode: locale })
- toast.success({ title: "Added to cart" })
+ await addToCart({
+ offerId: offer.id,
+ quantity: 1,
+ countryCode: locale,
+ optimisticItem: {
+ currencyCode: offer.calculated_price?.currency_code || "eur",
+ item: {
+ thumbnail: offer.product?.thumbnail || "",
+ product_title: offer.product?.title,
+ quantity: 1,
+ subtotal,
+ total,
+ tax_total: total - subtotal,
+ variant_id: offer.variant_id,
+ product_id: offer.product_id,
+ metadata: { offer_id: offer.id },
+ },
+ },
+ })
} catch (error) {
toast.error({
title: "Error adding to cart",
description: "This offer does not have the required inventory",
})
- } finally {
- setAddingId(null)
}
}
@@ -107,8 +126,7 @@ export const CompareOffersModal = ({
<Button
size="small"
onClick={() => handleAdd(offer)}
- disabled={!buyable || addingId !== null}
- loading={addingId === offer.id}
+ disabled={!buyable}
data-testid="compare-offer-add-to-cart"
>
Add to cart
diff --git a/apps/storefront/src/components/organisms/Header/Header.tsx b/apps/storefront/src/components/organisms/Header/Header.tsx
index 53a8b9baa..d19011fa0 100644
--- a/apps/storefront/src/components/organisms/Header/Header.tsx
+++ b/apps/storefront/src/components/organisms/Header/Header.tsx
@@ -1,7 +1,9 @@
import Image from "next/image"
+import { Suspense } from "react"
import { HttpTypes } from "@medusajs/types"
-import { CartDropdown, MobileNavbar, Navbar } from "@/components/cells"
+import { CartButton, MobileNavbar, Navbar } from "@/components/cells"
+import { CartIcon } from "@/icons"
import { UserDropdown } from "@/components/cells/UserDropdown/UserDropdown"
import CountrySelector from "@/components/molecules/CountrySelector/CountrySelector"
import LocalizedClientLink from "@/components/molecules/LocalizedLink/LocalizedLink"
@@ -14,15 +16,15 @@ import { ParentCategoryLinks } from "@/components/molecules/ParentCategoryLinks/
export const Header = async ({ locale } : {
locale: string
}) => {
- const user = await retrieveCustomer().catch(() => null)
+ const [user, regions, { categories, parentCategories }] = await Promise.all([
+ retrieveCustomer().catch(() => null),
+ listRegions(),
+ listCategories({ query: { include_ancestors_tree: true } }) as Promise<{
+ categories: HttpTypes.StoreProductCategory[]
+ parentCategories: HttpTypes.StoreProductCategory[]
+ }>,
+ ])
const isLoggedIn = Boolean(user)
-
- const regions = await listRegions()
-
- const { categories, parentCategories } = (await listCategories({ query: { include_ancestors_tree: true } })) as {
- categories: HttpTypes.StoreProductCategory[]
- parentCategories: HttpTypes.StoreProductCategory[]
- }
return (
<header data-testid="header">
<div className="flex py-2 lg:px-8 px-4 md:px-5" data-testid="header-top">
@@ -51,7 +53,15 @@ export const Header = async ({ locale } : {
<CountrySelector regions={regions} />
{isLoggedIn && <MessageButton />}
<UserDropdown isLoggedIn={isLoggedIn} />
- <CartDropdown />
+ <Suspense
+ fallback={
+ <LocalizedClientLink href="/cart" aria-label="Go to cart" className="flex">
+ <CartIcon size={20} />
+ </LocalizedClientLink>
+ }
+ >
+ <CartButton />
+ </Suspense>
</div>
</div>
<Navbar categories={categories} parentCategories={parentCategories} />
diff --git a/apps/storefront/src/components/organisms/OfferCard/OfferCard.tsx b/apps/storefront/src/components/organisms/OfferCard/OfferCard.tsx
index 4e270cdec..275b2c38d 100644
--- a/apps/storefront/src/components/organisms/OfferCard/OfferCard.tsx
+++ b/apps/storefront/src/components/organisms/OfferCard/OfferCard.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/atoms"
import { toast } from "@/lib/helpers/toast"
import LocalizedClientLink from "@/components/molecules/LocalizedLink/LocalizedLink"
import { useCartContext } from "@/components/providers"
+import { useCartDrawer } from "@/components/providers/Cart/drawer"
import { getOfferAmount, getOfferStock, type StoreOffer } from "@/lib/helpers/buybox"
import { convertToLocale } from "@/lib/helpers/money"
import { cn } from "@/lib/utils"
@@ -19,7 +20,8 @@ export const OfferCard = ({
locale: string
className?: string
}) => {
- const { addToCart, onAddToCart, cart, isAddingItem } = useCartContext()
+ const { addToCart, cart, isAddingItem } = useCartContext()
+ const { openDrawer } = useCartDrawer()
const product = offer.product
const productName = String(product?.title || "Product")
@@ -45,23 +47,28 @@ export const OfferCard = ({
const subtotal =
offer.calculated_price?.calculated_amount_without_tax ?? total
- onAddToCart(
- {
- thumbnail: product?.thumbnail || "",
- product_title: product?.title,
- quantity: 1,
- subtotal,
- total,
- tax_total: total - subtotal,
- variant_id: offer.variant_id,
- product_id: offer.product_id,
- metadata: { offer_id: offer.id },
- },
- currency
- )
+ openDrawer()
try {
- await addToCart({ offerId: offer.id, quantity: 1, countryCode: locale })
+ await addToCart({
+ offerId: offer.id,
+ quantity: 1,
+ countryCode: locale,
+ optimisticItem: {
+ currencyCode: currency,
+ item: {
+ thumbnail: product?.thumbnail || "",
+ product_title: product?.title,
+ quantity: 1,
+ subtotal,
+ total,
+ tax_total: total - subtotal,
+ variant_id: offer.variant_id,
+ product_id: offer.product_id,
+ metadata: { offer_id: offer.id },
+ },
+ },
+ })
} catch (error) {
toast.error({
title: "Error adding to cart",
diff --git a/apps/storefront/src/components/organisms/ProductDetails/ProductDetails.tsx b/apps/storefront/src/components/organisms/ProductDetails/ProductDetails.tsx
index 2ec123b0e..083395e5e 100644
--- a/apps/storefront/src/components/organisms/ProductDetails/ProductDetails.tsx
+++ b/apps/storefront/src/components/organisms/ProductDetails/ProductDetails.tsx
@@ -7,7 +7,6 @@ import {
ProductAdditionalAttributes,
} from "@/components/cells"
-import { retrieveCustomer } from "@/lib/data/customer"
import {
getBuyboxWinner,
rankOffers,
@@ -16,19 +15,19 @@ import {
import { AdditionalAttributeProps } from "@/types/product"
import { HttpTypes } from "@medusajs/types"
-export const ProductDetails = async ({
+export const ProductDetails = ({
product,
locale,
offers = [],
+ user,
}: {
product: HttpTypes.StoreProduct & {
attribute_values?: AdditionalAttributeProps[]
}
locale: string
offers?: StoreOffer[]
+ user: HttpTypes.StoreCustomer | null
}) => {
- const user = await retrieveCustomer()
-
// Master products have no seller; the seller shown comes from the buybox
// winning offer.
const seller = getBuyboxWinner(rankOffers(offers))?.seller
diff --git a/apps/storefront/src/components/providers/Cart/CartProvider.tsx b/apps/storefront/src/components/providers/Cart/CartProvider.tsx
index 966e57cbd..971cd111d 100644
--- a/apps/storefront/src/components/providers/Cart/CartProvider.tsx
+++ b/apps/storefront/src/components/providers/Cart/CartProvider.tsx
@@ -1,6 +1,6 @@
'use client';
-import { PropsWithChildren, useCallback, useEffect, useState } from 'react';
+import { PropsWithChildren, useOptimistic, useState, useTransition } from 'react';
import {
addToCart as apiAddToCart,
@@ -10,190 +10,182 @@ import {
} from '@/lib/data/cart';
import { Cart, StoreCartLineItemOptimisticUpdate } from '@/types/cart';
-import { CartContext } from './context';
+import { CartContext, type CartContextValue, getOfferPendingKey } from './context';
+import { CartDrawerProvider } from './drawer';
interface CartProviderProps extends PropsWithChildren {
- cart: Cart | null;
+ cartPromise: Promise<Cart | null>;
}
-export function CartProvider({ cart, children }: CartProviderProps) {
- const [cartState, setCartState] = useState(cart);
- const [isUpdating, setIsUpdating] = useState(false);
- const [isAddingItem, setIsAddingItem] = useState(false);
- const [isUpdatingItem, setIsUpdatingItem] = useState(false);
- const [isRemovingItem, setIsRemovingItem] = useState(false);
-
- useEffect(() => {
- setCartState(cart);
- }, [cart]);
-
- const refreshCart = useCallback(async () => {
- try {
- const cartData = await retrieveCart();
- setCartState(cartData);
- return cartData;
- } catch (error) {
- console.error('Error fetching cart:', error);
- return null;
- }
- }, []);
-
- function handleAddToCart(newItem: StoreCartLineItemOptimisticUpdate, currency_code: string) {
- setCartState(prev => {
- const currentItems = prev?.items || [];
- const isNewItemInCart = currentItems.find(
- ({ variant_id }) => variant_id === newItem.variant_id
- );
-
- if (isNewItemInCart) {
- const updatedItems = currentItems.map(currentItem => {
- if (currentItem.variant_id !== newItem.variant_id) {
- return currentItem;
- }
-
- const newQuantity = currentItem.quantity + (newItem?.quantity || 0);
- return {
- ...currentItem,
- quantity: newQuantity,
- subtotal: newQuantity * (newItem?.subtotal || 0),
- total: newQuantity * (newItem?.total || 0),
- tax_total: newQuantity * (newItem?.tax_total || 0)
- };
- }) as StoreCartLineItemOptimisticUpdate[];
-
- const { item_subtotal, total, tax_total } = getItemsSummaryValues(updatedItems);
-
- return {
- ...prev,
- items: updatedItems,
- item_subtotal,
- total,
- tax_total,
- currency_code
- } as Cart;
- }
-
- const updatedItems = [...currentItems, newItem] as StoreCartLineItemOptimisticUpdate[];
-
- const { item_subtotal, total, tax_total } = getItemsSummaryValues(updatedItems);
-
- return {
- ...prev,
- items: updatedItems,
- item_subtotal,
- total,
- tax_total,
- currency_code
- } as Cart;
- });
- }
+type OptimisticCartAction =
+ | { type: 'add'; item?: StoreCartLineItemOptimisticUpdate; currencyCode: string }
+ | { type: 'update'; lineId: string; quantity: number }
+ | { type: 'remove'; lineId: string };
+
+type LineItem = StoreCartLineItemOptimisticUpdate;
+
+function getItemsSummaryValues(items: LineItem[]) {
+ return items.reduce<{ item_subtotal: number; total: number; tax_total: number }>(
+ (acc, item) => ({
+ item_subtotal: acc.item_subtotal + (item.subtotal || 0),
+ total: acc.total + (item.total || 0),
+ tax_total: acc.tax_total + (item.tax_total || 0)
+ }),
+ { item_subtotal: 0, total: 0, tax_total: 0 }
+ );
+}
- const updateCartItem = async (lineId: string, quantity: number) => {
- if (!cartState?.items) return;
+function scaleLine(item: LineItem, quantity: number): LineItem {
+ const current = item.quantity || 0;
+ const ratio = current > 0 ? quantity / current : 0;
+ return {
+ ...item,
+ quantity,
+ subtotal: (item.subtotal || 0) * ratio,
+ total: (item.total || 0) * ratio,
+ tax_total: (item.tax_total || 0) * ratio
+ };
+}
- setIsUpdatingItem(true);
- setIsUpdating(true);
+function withItems(cart: Cart | null, items: LineItem[], currencyCode?: string): Cart {
+ return {
+ ...cart,
+ ...getItemsSummaryValues(items),
+ items,
+ ...(currencyCode ? { currency_code: currencyCode } : {})
+ } as Cart;
+}
- const optimisticCart = {
- ...cartState,
- items: cartState.items.map(item => (item.id === lineId ? { ...item, quantity } : item))
- };
+function applyOptimisticAction(cart: Cart | null, action: OptimisticCartAction): Cart | null {
+ const currentItems = (cart?.items || []) as LineItem[];
- setCartState(optimisticCart);
+ if (action.type === 'update') {
+ return withItems(
+ cart,
+ currentItems.map(item => (item.id === action.lineId ? scaleLine(item, action.quantity) : item))
+ );
+ }
- try {
- await apiUpdateLineItem({ lineId, quantity });
- await refreshCart();
- } catch (error) {
- console.error('Error updating item quantity:', error);
- await refreshCart();
- } finally {
- setIsUpdatingItem(false);
- setIsUpdating(false);
- }
- };
+ if (action.type === 'remove') {
+ return withItems(
+ cart,
+ currentItems.filter(item => item.id !== action.lineId)
+ );
+ }
- const addToCart = async ({
- offerId,
- quantity,
- countryCode
- }: {
- offerId: string;
- quantity: number;
- countryCode: string;
- }) => {
- setIsAddingItem(true);
- setIsUpdating(true);
-
- try {
- await apiAddToCart({
- offerId,
- quantity,
- countryCode
- });
- await refreshCart();
- } catch (error) {
- console.error('Error adding product to cart:', error);
- await refreshCart();
- throw error;
- } finally {
- setIsAddingItem(false);
- setIsUpdating(false);
- }
- };
+ const { item: newItem, currencyCode } = action;
+ if (!newItem) return cart;
+
+ const offerId = newItem.metadata?.offer_id;
+ const existing = currentItems.find(item => item.metadata?.offer_id === offerId);
+
+ const items = existing
+ ? currentItems.map(item =>
+ item === existing
+ ? scaleLine(item, (item.quantity || 0) + (newItem.quantity || 0))
+ : item
+ )
+ : [...currentItems, { ...newItem, id: `optimistic:${offerId}` }];
- const removeCartItem = async (lineId: string) => {
- if (!cartState?.items) return;
+ return withItems(cart, items, currencyCode);
+}
- setIsRemovingItem(true);
- setIsUpdating(true);
+export function CartProvider({ cartPromise, children }: CartProviderProps) {
+ const [seed, setSeed] = useState(cartPromise);
+ // undefined = no mutation yet: read the streamed seed, which a revalidated layout replaces.
+ const [confirmedCart, setConfirmedCart] = useState<Cart | null | undefined>(undefined);
- const optimisticCart = {
- ...cartState,
- items: cartState.items.filter(item => item.id !== lineId)
- };
+ if (seed !== cartPromise) {
+ setSeed(cartPromise);
+ setConfirmedCart(undefined);
+ }
- setCartState(optimisticCart);
+ const [optimisticCart, applyOptimistic] = useOptimistic<
+ Cart | null | undefined,
+ OptimisticCartAction
+ >(confirmedCart, (cart, action) =>
+ cart === undefined ? cart : applyOptimisticAction(cart, action)
+ );
- try {
- await apiDeleteLineItem(lineId);
- await refreshCart();
- } catch (error) {
- console.error('Error removing item from cart:', error);
- await refreshCart();
- } finally {
- setIsRemovingItem(false);
- setIsUpdating(false);
+ const [pendingKeys, markPending] = useOptimistic<string[], string>([], (keys, key) => [
+ ...keys,
+ key
+ ]);
+
+ const [isAddingItem, startAdding] = useTransition();
+ const [isUpdatingItem, startUpdating] = useTransition();
+ const [isRemovingItem, startRemoving] = useTransition();
+
+ const transitions = { add: startAdding, remove: startRemoving, update: startUpdating };
+
+ const mutate = (
+ seededCart: Cart | null,
+ optimisticAction: OptimisticCartAction,
+ pendingKey: string,
+ mutation: () => Promise<Cart | null>
+ ) => {
+ if (confirmedCart === undefined) {
+ setConfirmedCart(seededCart);
}
+
+ const start = transitions[optimisticAction.type];
+
+ return new Promise<void>((resolve, reject) => {
+ start(async () => {
+ applyOptimistic(optimisticAction);
+ markPending(pendingKey);
+
+ try {
+ const cart = await mutation();
+ start(() => setConfirmedCart(cart));
+ resolve();
+ } catch (error) {
+ const cart = await retrieveCart().catch(() => null);
+ start(() => setConfirmedCart(cart));
+ reject(error);
+ }
+ });
+ });
};
- function getItemsSummaryValues(items: StoreCartLineItemOptimisticUpdate[]) {
- return items.reduce(
- (acc, item) => ({
- item_subtotal: (acc.item_subtotal || 0) + (item.subtotal || 0),
- total: (acc.total || 0) + (item.total || 0),
- tax_total: (acc.tax_total || 0) + (item.tax_total || 0)
- }),
- { item_subtotal: 0, total: 0, tax_total: 0 }
+ const addToCart: CartContextValue['addToCart'] = (
+ seededCart,
+ { offerId, optimisticItem, quantity, countryCode }
+ ) =>
+ mutate(
+ seededCart,
+ {
+ currencyCode: optimisticItem?.currencyCode || seededCart?.currency_code || '',
+ item: optimisticItem?.item,
+ type: 'add'
+ },
+ getOfferPendingKey(offerId),
+ () => apiAddToCart({ countryCode, offerId, quantity })
);
- }
+
+ const updateCartItem: CartContextValue['updateCartItem'] = (seededCart, lineId, quantity) =>
+ mutate(seededCart, { lineId, quantity, type: 'update' }, lineId, () =>
+ apiUpdateLineItem({ lineId, quantity })
+ );
+
+ const removeCartItem: CartContextValue['removeCartItem'] = (seededCart, lineId) =>
+ mutate(seededCart, { lineId, type: 'remove' }, lineId, () => apiDeleteLineItem(lineId));
return (
<CartContext.Provider
value={{
- cart: cartState,
- onAddToCart: handleAddToCart,
addToCart,
- removeCartItem,
- updateCartItem,
- refreshCart,
- isUpdating,
+ cartPromise: seed,
isAddingItem,
+ isRemovingItem,
isUpdatingItem,
- isRemovingItem
+ optimisticCart,
+ pendingKeys,
+ removeCartItem,
+ updateCartItem
}}
>
- {children}
+ <CartDrawerProvider>{children}</CartDrawerProvider>
</CartContext.Provider>
);
}
diff --git a/apps/storefront/src/components/providers/Cart/context.tsx b/apps/storefront/src/components/providers/Cart/context.tsx
index b78c988c0..66383370e 100644
--- a/apps/storefront/src/components/providers/Cart/context.tsx
+++ b/apps/storefront/src/components/providers/Cart/context.tsx
@@ -1,32 +1,59 @@
'use client';
-import { createContext, useContext } from 'react';
+import { createContext, use, useContext } from 'react';
import { Cart, StoreCartLineItemOptimisticUpdate } from '@/types/cart';
-interface CartContextInterface {
- cart: Cart | null;
- onAddToCart: (item: StoreCartLineItemOptimisticUpdate, currency_code: string) => void;
- addToCart: (params: {
- offerId: string;
- quantity: number;
- countryCode: string;
- }) => Promise<void>;
- removeCartItem: (lineId: string) => Promise<void>;
- updateCartItem: (lineId: string, quantity: number) => Promise<void>;
- refreshCart: () => Promise<Cart | null>;
- isUpdating: boolean;
+interface AddToCartParams {
+ countryCode: string;
+ offerId: string;
+ optimisticItem?: { currencyCode: string; item: StoreCartLineItemOptimisticUpdate };
+ quantity: number;
+}
+
+export interface CartContextValue {
+ addToCart: (seededCart: Cart | null, params: AddToCartParams) => Promise<void>;
+ cartPromise: Promise<Cart | null>;
isAddingItem: boolean;
- isUpdatingItem: boolean;
isRemovingItem: boolean;
+ isUpdatingItem: boolean;
+ optimisticCart: Cart | null | undefined;
+ pendingKeys: string[];
+ removeCartItem: (seededCart: Cart | null, lineId: string) => Promise<void>;
+ updateCartItem: (seededCart: Cart | null, lineId: string, quantity: number) => Promise<void>;
}
-export const CartContext = createContext<CartContextInterface | null>(null);
+export const CartContext = createContext<CartContextValue | null>(null);
+export const getOfferPendingKey = (offerId: string) => `offer:${offerId}`;
+
+// Suspends until the streamed server cart resolves, so callers that render cart
+// data belong under a Suspense boundary whose fallback matches their geometry.
export function useCartContext() {
const context = useContext(CartContext);
if (!context) {
throw new Error('useCartContext must be used within a CartProvider');
}
- return context;
+
+ const seededCart = use(context.cartPromise);
+ const cart = context.optimisticCart === undefined ? seededCart : context.optimisticCart;
+
+ return {
+ addToCart: (params: AddToCartParams) => context.addToCart(seededCart, params),
+ cart,
+ isAddingItem: context.isAddingItem,
+ isLinePending: (line: { id?: string; metadata?: Record<string, unknown> | null }) => {
+ const offerId = line.metadata?.offer_id;
+ return (
+ (!!line.id && context.pendingKeys.includes(line.id)) ||
+ (typeof offerId === 'string' && context.pendingKeys.includes(getOfferPendingKey(offerId)))
+ );
+ },
+ isRemovingItem: context.isRemovingItem,
+ isUpdating: context.isAddingItem || context.isRemovingItem || context.isUpdatingItem,
+ isUpdatingItem: context.isUpdatingItem,
+ removeCartItem: (lineId: string) => context.removeCartItem(seededCart, lineId),
+ updateCartItem: (lineId: string, quantity: number) =>
+ context.updateCartItem(seededCart, lineId, quantity)
+ };
}
diff --git a/apps/storefront/src/components/providers/Cart/drawer.tsx b/apps/storefront/src/components/providers/Cart/drawer.tsx
new file mode 100644
index 000000000..469c8cdc3
--- /dev/null
+++ b/apps/storefront/src/components/providers/Cart/drawer.tsx
@@ -0,0 +1,31 @@
+'use client';
+
+import { createContext, PropsWithChildren, useCallback, useContext, useState } from 'react';
+
+interface CartDrawerContextValue {
+ closeDrawer: () => void;
+ isDrawerOpen: boolean;
+ openDrawer: () => void;
+}
+
+const CartDrawerContext = createContext<CartDrawerContextValue | null>(null);
+
+export function CartDrawerProvider({ children }: PropsWithChildren) {
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const openDrawer = useCallback(() => setIsDrawerOpen(true), []);
+ const closeDrawer = useCallback(() => setIsDrawerOpen(false), []);
+
+ return (
+ <CartDrawerContext.Provider value={{ closeDrawer, isDrawerOpen, openDrawer }}>
+ {children}
+ </CartDrawerContext.Provider>
+ );
+}
+
+export function useCartDrawer() {
+ const context = useContext(CartDrawerContext);
+ if (!context) {
+ throw new Error('useCartDrawer must be used within a CartProvider');
+ }
+ return context;
+}
diff --git a/apps/storefront/src/components/sections/ProductDetailsPage/ProductDetailsPage.tsx b/apps/storefront/src/components/sections/ProductDetailsPage/ProductDetailsPage.tsx
index 9c6845e40..54d6adc56 100644
--- a/apps/storefront/src/components/sections/ProductDetailsPage/ProductDetailsPage.tsx
+++ b/apps/storefront/src/components/sections/ProductDetailsPage/ProductDetailsPage.tsx
@@ -1,6 +1,7 @@
import { ProductDetails, ProductGallery } from "@/components/organisms"
import { listProducts } from "@/lib/data/products"
import { listOffers } from "@/lib/data/offers"
+import { retrieveCustomer } from "@/lib/data/customer"
import { StoreOffer } from "@/lib/helpers/buybox"
import { HomeProductSection } from "../HomeProductSection/HomeProductSection"
import NotFound from "@/app/not-found"
@@ -12,6 +13,8 @@ export const ProductDetailsPage = async ({
handle: string
locale: string
}) => {
+ const userPromise = retrieveCustomer()
+
const prod = await listProducts({
countryCode: locale,
queryParams: { handle: [handle], limit: 1 },
@@ -23,10 +26,10 @@ export const ProductDetailsPage = async ({
return NotFound()
}
- const { offers } = await listOffers({
- productId: prod.id,
- countryCode: locale,
- })
+ const [{ offers }, user] = await Promise.all([
+ listOffers({ productId: prod.id, countryCode: locale }),
+ userPromise,
+ ])
return (
<>
@@ -39,6 +42,7 @@ export const ProductDetailsPage = async ({
product={prod}
locale={locale}
offers={offers as StoreOffer[]}
+ user={user}
/>
</div>
</div>
@@ -52,3 +56,18 @@ export const ProductDetailsPage = async ({
</>
)
}
+
+export const ProductDetailsPageSkeleton = () => (
+ <div
+ aria-busy="true"
+ className="flex flex-col md:flex-row lg:gap-12"
+ data-testid="product-details-page-skeleton"
+ >
+ <div className="md:w-1/2 md:px-2">
+ <div className="aspect-square w-full animate-pulse rounded-sm bg-component-secondary" />
+ </div>
+ <div className="md:w-1/2 md:px-2">
+ <div className="h-64 w-full animate-pulse rounded-sm border bg-component-secondary" />
+ </div>
+ </div>
+)
diff --git a/apps/storefront/src/lib/data/cache-tags.ts b/apps/storefront/src/lib/data/cache-tags.ts
index 38cff337c..1e152b198 100644
--- a/apps/storefront/src/lib/data/cache-tags.ts
+++ b/apps/storefront/src/lib/data/cache-tags.ts
@@ -18,6 +18,8 @@ export const CACHE_TAGS = {
collection: (handle: string) => `collection-${handle}`,
categories: 'categories',
category: (handle: string) => `category-${handle}`,
+ sellers: 'sellers',
+ seller: (handle: string) => `seller-${handle}`,
} as const;
/**
diff --git a/apps/storefront/src/lib/data/cart.ts b/apps/storefront/src/lib/data/cart.ts
index a1df0a418..320e72c24 100644
--- a/apps/storefront/src/lib/data/cart.ts
+++ b/apps/storefront/src/lib/data/cart.ts
@@ -66,9 +66,6 @@ export async function getOrSetCart(countryCode: string) {
cart = cartResp.cart;
await setCartId(cart.id);
-
- const cartCacheTag = await getCacheTag('carts');
- revalidateTag(cartCacheTag);
}
if (cart && cart?.region_id !== region.id) {
@@ -77,8 +74,6 @@ export async function getOrSetCart(countryCode: string) {
region_id: region.id,
fetchOptions: { headers }
});
- const cartCacheTag = await getCacheTag('carts');
- revalidateTag(cartCacheTag);
}
return cart;
@@ -105,6 +100,9 @@ export async function updateCart(data: HttpTypes.StoreUpdateCart) {
.catch(medusaError);
}
+// Line-item actions return the refreshed cart instead of revalidating: carts are
+// never in the data cache, and a revalidate inside a Server Action re-renders the
+// whole current route on every quantity change.
export async function addToCart({
offerId,
quantity,
@@ -143,11 +141,7 @@ export async function addToCart({
quantity: currentItem.quantity + quantity,
fetchOptions: { headers }
})
- .catch(medusaError)
- .finally(async () => {
- const cartCacheTag = await getCacheTag('carts');
- revalidateTag(cartCacheTag);
- });
+ .catch(medusaError);
} else {
await (sdk.store.carts.$id.lineItems
.mutate({
@@ -156,16 +150,10 @@ export async function addToCart({
quantity,
fetchOptions: { headers }
} as never) as unknown as Promise<{ cart: HttpTypes.StoreCart }>)
- .then(async () => {
- const cartCacheTag = await getCacheTag('carts');
- revalidateTag(cartCacheTag);
- })
- .catch(medusaError)
- .finally(async () => {
- const cartCacheTag = await getCacheTag('carts');
- revalidateTag(cartCacheTag);
- });
+ .catch(medusaError);
}
+
+ return retrieveCart(cart.id);
}
export async function updateLineItem({ lineId, quantity }: { lineId: string; quantity: number }) {
@@ -183,17 +171,16 @@ export async function updateLineItem({ lineId, quantity }: { lineId: string; qua
...(await getAuthHeaders())
};
- const res = await sdk.store.carts.$id.lineItems.$lineId.mutate({
- $id: cartId,
- $lineId: lineId,
- quantity,
- fetchOptions: { headers }
- });
-
- const cartCacheTag = await getCacheTag('carts');
- await revalidateTag(cartCacheTag);
+ await sdk.store.carts.$id.lineItems.$lineId
+ .mutate({
+ $id: cartId,
+ $lineId: lineId,
+ quantity,
+ fetchOptions: { headers }
+ })
+ .catch(medusaError);
- return res;
+ return retrieveCart(cartId);
}
export async function deleteLineItem(lineId: string) {
@@ -213,11 +200,9 @@ export async function deleteLineItem(lineId: string) {
await sdk.store.carts.$id.lineItems.$lineId
.delete({ $id: cartId, $lineId: lineId, fetchOptions: { headers } })
- .then(async () => {
- const cartCacheTag = await getCacheTag('carts');
- await revalidateTag(cartCacheTag);
- })
.catch(medusaError);
+
+ return retrieveCart(cartId);
}
export async function setShippingMethod({
diff --git a/apps/storefront/src/lib/data/customer.ts b/apps/storefront/src/lib/data/customer.ts
index 4ed1c6331..d184c92ee 100644
--- a/apps/storefront/src/lib/data/customer.ts
+++ b/apps/storefront/src/lib/data/customer.ts
@@ -17,7 +17,7 @@ import {
export const retrieveCustomer = async (): Promise<HttpTypes.StoreCustomer | null> => {
const authHeaders = await getAuthHeaders();
- if (!authHeaders) return null;
+ if (!('authorization' in authHeaders)) return null;
const headers = {
...authHeaders
diff --git a/apps/storefront/src/lib/data/seller.ts b/apps/storefront/src/lib/data/seller.ts
index bd0da55d0..06bdc0db0 100644
--- a/apps/storefront/src/lib/data/seller.ts
+++ b/apps/storefront/src/lib/data/seller.ts
@@ -1,6 +1,7 @@
import { SellerDTO } from '@mercurjs/types';
import { sdk } from '../client';
+import { CACHE_TAGS } from './cache-tags';
const SELLER_FIELDS =
'id,name,handle,description,logo,banner,is_premium,metadata,created_at,email,phone';
@@ -12,7 +13,12 @@ export const getSellerByHandle = async (
sdk.store.sellers.query({
handle,
fields: SELLER_FIELDS,
- fetchOptions: { cache: 'no-cache' },
+ fetchOptions: {
+ next: {
+ revalidate: 300,
+ tags: [CACHE_TAGS.sellers, CACHE_TAGS.seller(handle)],
+ },
+ },
} as never) as unknown as Promise<{ sellers: SellerDTO[] }>
)
.then(({ sellers }) => sellers.find((s) => s.handle === handle) ?? null)