'use client'; import { Dialog, Transition } from '@headlessui/react'; import Image from 'next/image'; import Link from 'next/link'; import CartIcon from 'components/icons/cart'; 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 { createUrl } from 'lib/utils'; import { Fragment, useEffect, useRef, useState } from 'react'; import { useCookies } from 'react-cookie'; import DeleteItemButton from './delete-item-button'; import EditItemQuantityButton from './edit-item-quantity-button'; type MerchandiseSearchParams = { [key: string]: string; }; export default function CartModal({ cart, cartIdUpdated }: { cart: Cart; cartIdUpdated: boolean }) { const [, setCookie] = useCookies(['cartId']); const [isOpen, setIsOpen] = useState(false); const quantityRef = useRef(cart.totalQuantity); const openCart = () => setIsOpen(true); const closeCart = () => setIsOpen(false); 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 (!isOpen) { setIsOpen(true); } // Always update the quantity reference quantityRef.current = cart.totalQuantity; } }, [isOpen, cart.totalQuantity, quantityRef]); return ( <> ); }