{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"add-to-cart","title":"Add to Cart","author":"CoDesign-Spa27","description":"An interactive product grid with curved add-to-cart flights, a responsive cart stack, and an animated currency total.","dependencies":["@number-flow/react","motion","next"],"files":[{"path":"components/ui-components/add-to-cart.tsx","content":"\"use client\";\n\nimport NumberFlow from \"@number-flow/react\";\nimport { arc, motion, useReducedMotion } from \"motion/react\";\nimport Image from \"next/image\";\nimport { type ReactNode, useCallback, useMemo, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type AddToCartItem = {\n  id: number;\n  image: string;\n  price: number;\n  alt: string;\n};\n\nexport type AddToCartImage =\n  | string\n  | {\n      src: string;\n      alt?: string;\n    };\n\nexport type AddToCartLayout = {\n  columns?: 2 | 3 | 4;\n  gap?: \"compact\" | \"default\" | \"roomy\";\n  showBorder?: boolean;\n  stackLimit?: number;\n  stackSpread?: number;\n};\n\nexport type AddToCartMotion = {\n  duration?: number;\n  peak?: number;\n  strength?: number;\n  tapScale?: number;\n};\n\ntype Flight = {\n  id: number;\n  item: AddToCartItem;\n\n  // Starting position\n  left: number;\n  top: number;\n\n  // Distance to cart\n  x: number;\n  y: number;\n\n  width: number;\n  height: number;\n};\n\ntype ProductTileProps = {\n  item: AddToCartItem;\n  added: boolean;\n  disabled: boolean;\n  priceLabel: string;\n  imageSizes: string;\n  tapScale: number;\n  shouldReduceMotion: boolean;\n  onAdd: (item: AddToCartItem, source: DOMRect) => void;\n};\n\nexport type AddToCartProps = {\n  cartIcon?: ReactNode;\n  cartLabel?: string;\n  className?: string;\n  currency?: string;\n  disabled?: boolean;\n  imageSizes?: string;\n  images?: readonly AddToCartImage[];\n  initialItems?: readonly number[];\n  items?: readonly AddToCartItem[];\n  layout?: AddToCartLayout;\n  locale?: string | string[];\n  motion?: AddToCartMotion;\n  onCartChange?: (items: readonly AddToCartItem[], total: number) => void;\n  onItemAdd?: (item: AddToCartItem) => void;\n};\n\nexport const ADD_TO_CART_ITEMS = [\n  {\n    id: 1,\n    image: \"/images/add-to-cart/image1.png\",\n    price: 150,\n    alt: \"Pink and blue marbled artwork\",\n  },\n  {\n    id: 2,\n    image: \"/images/add-to-cart/image2.png\",\n    price: 360,\n    alt: \"Pastel orbital artwork\",\n  },\n  {\n    id: 3,\n    image: \"/images/add-to-cart/image3.png\",\n    price: 100,\n    alt: \"Blue ink cloud artwork\",\n  },\n  {\n    id: 4,\n    image: \"/images/add-to-cart/image4.png\",\n    price: 432,\n    alt: \"Turquoise and yellow flowing artwork\",\n  },\n  {\n    id: 5,\n    image: \"/images/add-to-cart/image5.png\",\n    price: 460,\n    alt: \"Mountain landscape at night\",\n  },\n  {\n    id: 6,\n    image: \"/images/add-to-cart/image6.png\",\n    price: 970,\n    alt: \"Blue and white painted artwork\",\n  },\n  {\n    id: 7,\n    image: \"/images/add-to-cart/image7.png\",\n    price: 720,\n    alt: \"Purple and cyan wave artwork\",\n  },\n  {\n    id: 8,\n    image: \"/images/add-to-cart/image8.png\",\n    price: 633,\n    alt: \"Pink and blue light artwork\",\n  },\n] as const satisfies readonly AddToCartItem[];\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nconst EMPTY_IMAGES: readonly AddToCartImage[] = [];\nconst EMPTY_INITIAL_ITEMS: readonly number[] = [];\n\nconst COLUMN_CLASSES = {\n  2: \"grid-cols-2\",\n  3: \"grid-cols-2 sm:grid-cols-3\",\n  4: \"grid-cols-2 sm:grid-cols-4\",\n} as const;\n\nconst GAP_CLASSES = {\n  compact: \"gap-2\",\n  default: \"gap-3 sm:gap-4\",\n  roomy: \"gap-4 sm:gap-6\",\n} as const;\n\nconst tileVariants = {\n  idle: {\n    filter: \"blur(0px)\",\n    opacity: 1,\n    scale: 1,\n  },\n\n  hover: {\n    filter: \"blur(3px)\",\n    opacity: 0.48,\n    scale: 1.025,\n  },\n\n  added: {\n    filter: \"blur(1.5px)\",\n    opacity: 0.58,\n    scale: 1,\n  },\n};\n\nconst affordanceVariants = {\n  idle: {\n    opacity: 0,\n    scale: 0.94,\n  },\n\n  hover: {\n    opacity: 1,\n    scale: 1,\n  },\n\n  added: {\n    opacity: 1,\n    scale: 1,\n  },\n};\n\nfunction ProductTile({\n  item,\n  added,\n  disabled,\n  priceLabel,\n  imageSizes,\n  tapScale,\n  shouldReduceMotion,\n  onAdd,\n}: ProductTileProps) {\n  return (\n    <motion.button\n      type=\"button\"\n      initial={false}\n      disabled={added || disabled}\n      animate={added ? \"added\" : \"idle\"}\n      whileHover={added || disabled ? undefined : \"hover\"}\n      whileFocus={added || disabled ? undefined : \"hover\"}\n      whileTap={added || disabled || shouldReduceMotion ? undefined : { scale: tapScale }}\n      onClick={(event) => {\n        onAdd(item, event.currentTarget.getBoundingClientRect());\n      }}\n      aria-label={added ? `${item.alt} added to cart` : `Add ${item.alt} for ${priceLabel}`}\n      className=\"\n        group relative aspect-square min-w-0\n        overflow-hidden rounded-lg bg-neutral-300/20\n        outline-none ring-offset-2 ring-offset-neutral-950\n        focus-visible:ring-2 focus-visible:ring-white/80\n        disabled:cursor-default\n      \"\n    >\n      <motion.div\n        className=\"absolute inset-0\"\n        variants={tileVariants}\n        transition={{\n          duration: shouldReduceMotion ? 0 : 0.18,\n          ease: EASE_OUT,\n        }}\n      >\n        <Image\n          fill\n          draggable={false}\n          src={item.image}\n          alt={item.alt}\n          sizes={imageSizes}\n          className=\"object-cover\"\n        />\n      </motion.div>\n\n      <motion.span\n        aria-hidden=\"true\"\n        variants={affordanceVariants}\n        transition={{\n          duration: shouldReduceMotion ? 0 : 0.18,\n          ease: EASE_OUT,\n        }}\n        className=\"\n          absolute inset-0\n          flex items-center justify-center\n          bg-neutral-100/10\n          [@media(hover:none)]:opacity-100\n        \"\n      >\n        <span\n          className=\"\n            flex size-7 items-center justify-center\n            rounded-full bg-white text-neutral-950\n            shadow-[0_4px_8px_rgb(0_0_0/0.18)]\n          \"\n        >\n          {added ? <CheckIcon className=\"size-5\" /> : <PlusIcon className=\"size-5\" />}\n        </span>\n      </motion.span>\n    </motion.button>\n  );\n}\n\ntype ArcPath = ReturnType<typeof arc>;\n\nfunction FlyingProduct({\n  flight,\n  duration,\n  path,\n  onComplete,\n}: {\n  flight: Flight;\n  duration: number;\n  path: ArcPath;\n  onComplete: () => void;\n}) {\n  return (\n    <motion.div\n      aria-hidden=\"true\"\n      initial={{\n        x: 0,\n        y: 0,\n        scale: 1,\n        opacity: 1,\n      }}\n      animate={{\n        x: flight.x,\n        y: flight.y,\n\n        scale: [1, 0.78, 0.18],\n        opacity: [1, 1, 0.72],\n      }}\n      transition={{\n        duration,\n        ease: EASE_IN_OUT,\n\n        // Motion handles the curved trajectory.\n        path,\n\n        scale: {\n          duration,\n          ease: EASE_IN_OUT,\n          times: [0, 0.55, 1],\n        },\n\n        opacity: {\n          duration,\n          ease: EASE_IN_OUT,\n          times: [0, 0.78, 1],\n        },\n      }}\n      onAnimationComplete={onComplete}\n      style={{\n        left: flight.left,\n        top: flight.top,\n        width: flight.width,\n        height: flight.height,\n      }}\n      className=\"\n        pointer-events-none fixed z-[70]\n        overflow-hidden rounded-xl\n        shadow-[0_6px_12px_rgb(0_0_0/0.24)]\n      \"\n    >\n      <Image\n        fill\n        alt=\"\"\n        src={flight.item.image}\n        sizes={`${Math.round(flight.width)}px`}\n        className=\"object-cover\"\n      />\n    </motion.div>\n  );\n}\n\nconst STACK_SPRING = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 28,\n  mass: 0.75,\n} as const;\n\nfunction getStackPosition(index: number, count: number, expanded: boolean, spread: number) {\n  const center = (count - 1) / 2;\n  const offset = index - center;\n\n  if (!expanded) {\n    return {\n      x: offset * 3,\n      y: 4 + Math.abs(offset) * 4,\n      rotate: offset * 7,\n    };\n  }\n  const maxDistance = Math.max(center, 1);\n  const distanceFromCenter = Math.abs(offset) / maxDistance;\n\n  return {\n    x: offset * spread,\n    y: -spread * 0.8 - (1 - distanceFromCenter) * spread,\n\n    rotate: offset * 12,\n  };\n}\n\nfunction CartStack({\n  cart,\n  icon,\n  limit,\n  spread,\n  shouldReduceMotion,\n}: {\n  cart: AddToCartItem[];\n  icon: ReactNode;\n  limit: number;\n  spread: number;\n  shouldReduceMotion: boolean;\n}) {\n  const [hovered, setHovered] = useState(false);\n\n  const items = cart.slice(-limit);\n\n  return (\n    <motion.div\n      className=\"relative flex size-14 shrink-0 items-center justify-center\"\n      onHoverStart={() => setHovered(true)}\n      onHoverEnd={() => setHovered(false)}\n    >\n      <div\n        aria-hidden=\"true\"\n        className=\"\n          pointer-events-none\n          absolute\n          left-1/2\n          top-[18px]\n          z-0\n          size-0\n        \"\n      >\n        {items.map((item, index) => {\n          const position = getStackPosition(index, items.length, hovered, spread);\n\n          return (\n            <motion.div\n              key={item.id}\n              initial={\n                shouldReduceMotion\n                  ? false\n                  : {\n                      opacity: 0,\n                      y: 0,\n                    }\n              }\n              animate={{\n                opacity: 1,\n                x: position.x,\n                y: position.y,\n                rotate: position.rotate,\n              }}\n              transition={shouldReduceMotion ? { duration: 0 } : STACK_SPRING}\n              style={{\n                zIndex: index,\n              }}\n              className=\"\n                absolute\n                -left-[8px]\n                -top-[18px]\n                size-5\n                overflow-hidden\n                rounded-[4px]\n                border\n                border-background\n                shadow-sm\n                will-change-transform\n              \"\n            >\n              <Image fill alt=\"\" src={item.image} sizes=\"36px\" className=\"object-cover\" />\n            </motion.div>\n          );\n        })}\n      </div>\n\n      <div className=\"relative z-10 flex size-12 items-center justify-center\">{icon}</div>\n    </motion.div>\n  );\n}\n\nexport function AddToCart({\n  cartIcon = <CartIcon className=\"size-full\" />,\n  cartLabel = \"Cart total\",\n  className,\n  currency = \"USD\",\n  disabled = false,\n  imageSizes = \"(min-width: 640px) 5rem, 40vw\",\n  images = EMPTY_IMAGES,\n  initialItems = EMPTY_INITIAL_ITEMS,\n  items = ADD_TO_CART_ITEMS,\n  layout,\n  locale = \"en-US\",\n  motion: motionOptions,\n  onCartChange,\n  onItemAdd,\n}: AddToCartProps) {\n  const shouldReduceMotion = Boolean(useReducedMotion());\n\n  const columns = layout?.columns ?? 4;\n  const gap = layout?.gap ?? \"default\";\n  const showBorder = layout?.showBorder ?? true;\n  const stackLimit = Math.max(1, Math.round(layout?.stackLimit ?? 5));\n  const stackSpread = Math.max(0, layout?.stackSpread ?? 20);\n  const flightDuration = Math.max(0, motionOptions?.duration ?? 0.58);\n  const flightPeak = motionOptions?.peak ?? 0.42;\n  const flightStrength = motionOptions?.strength ?? 0.32;\n  const tapScale = motionOptions?.tapScale ?? 0.96;\n\n  const catalog = useMemo(\n    () =>\n      items.map((item, index) => {\n        const image = images[index];\n\n        if (!image) return item;\n\n        return {\n          ...item,\n          image: typeof image === \"string\" ? image : image.src,\n          alt: typeof image === \"string\" ? item.alt : (image.alt ?? item.alt),\n        };\n      }),\n    [images, items],\n  );\n\n  const cartTargetRef = useRef<HTMLDivElement>(null);\n  const nextFlightIdRef = useRef(0);\n\n  const [cartIds, setCartIds] = useState<number[]>(() => [...new Set(initialItems)]);\n  const cartIdsRef = useRef(cartIds);\n\n  const [flights, setFlights] = useState<Flight[]>([]);\n\n  const catalogById = useMemo(() => new Map(catalog.map((item) => [item.id, item])), [catalog]);\n\n  const cart = useMemo(\n    () =>\n      cartIds.flatMap((id) => {\n        const item = catalogById.get(id);\n        return item ? [item] : [];\n      }),\n    [cartIds, catalogById],\n  );\n\n  /*\n   * Reusing the same arc instance is recommended\n   * when Motion chooses the direction automatically.\n   *\n   * strength -> how curved the path is\n   * peak     -> where the curve reaches its highest point\n   */\n  const flightPath = useMemo(\n    () =>\n      arc({\n        strength: flightStrength,\n        peak: flightPeak,\n      }),\n    [flightPeak, flightStrength],\n  );\n\n  const selectedIds = useMemo(() => {\n    return new Set([...cartIds, ...flights.map((flight) => flight.item.id)]);\n  }, [cartIds, flights]);\n\n  const total = useMemo(() => {\n    return cart.reduce((sum, item) => sum + item.price, 0);\n  }, [cart]);\n\n  const priceFormatter = useMemo(\n    () =>\n      new Intl.NumberFormat(locale, {\n        style: \"currency\",\n        currency,\n        currencyDisplay: \"narrowSymbol\",\n        minimumFractionDigits: 0,\n      }),\n    [currency, locale],\n  );\n\n  const commitItem = useCallback(\n    (item: AddToCartItem) => {\n      if (cartIdsRef.current.includes(item.id)) return;\n\n      const nextIds = [...cartIdsRef.current, item.id];\n      const nextItems = nextIds.flatMap((id) => {\n        const catalogItem = catalogById.get(id);\n        return catalogItem ? [catalogItem] : [];\n      });\n\n      cartIdsRef.current = nextIds;\n      setCartIds(nextIds);\n      onItemAdd?.(item);\n      onCartChange?.(\n        nextItems,\n        nextItems.reduce((sum, nextItem) => sum + nextItem.price, 0),\n      );\n    },\n    [catalogById, onCartChange, onItemAdd],\n  );\n\n  const addToCart = (item: AddToCartItem, source: DOMRect) => {\n    if (disabled || selectedIds.has(item.id)) return;\n\n    const target = cartTargetRef.current?.getBoundingClientRect();\n\n    /*\n     * Accessibility:\n     * Don't animate the flight when the user\n     * prefers reduced motion.\n     */\n    if (shouldReduceMotion || !target) {\n      commitItem(item);\n      return;\n    }\n\n    const startX = source.left + source.width / 2;\n\n    const startY = source.top + source.height / 2;\n\n    const endX = target.left + target.width / 2;\n\n    const endY = target.top + target.height / 2;\n\n    nextFlightIdRef.current += 1;\n\n    setFlights((current) => [\n      ...current,\n      {\n        id: nextFlightIdRef.current,\n        item,\n\n        left: source.left,\n        top: source.top,\n\n        /*\n         * We only give Motion the destination.\n         * arc() generates the curved path.\n         */\n        x: endX - startX,\n        y: endY - startY,\n\n        width: source.width,\n        height: source.height,\n      },\n    ]);\n  };\n\n  const finishFlight = (flight: Flight) => {\n    setFlights((current) => current.filter((candidate) => candidate.id !== flight.id));\n\n    commitItem(flight.item);\n  };\n\n  return (\n    <div\n      className={cn(\n        `\n          w-full max-w-[26rem]\n          rounded-3xl\n          p-5 text-foreground\n        `,\n        showBorder && \"border\",\n        className,\n      )}\n    >\n      <div className={cn(\"grid\", COLUMN_CLASSES[columns], GAP_CLASSES[gap])}>\n        {catalog.map((item) => (\n          <ProductTile\n            key={item.id}\n            item={item}\n            added={selectedIds.has(item.id)}\n            disabled={disabled}\n            imageSizes={imageSizes}\n            priceLabel={priceFormatter.format(item.price)}\n            shouldReduceMotion={shouldReduceMotion}\n            tapScale={tapScale}\n            onAdd={addToCart}\n          />\n        ))}\n      </div>\n\n      <div\n        className=\"\n          mt-4 flex min-h-20\n          items-center justify-between gap-5\n        \"\n      >\n        <div className=\"flex min-w-0 items-center gap-4\">\n          <div ref={cartTargetRef} className=\"relative\">\n            <CartStack\n              cart={cart}\n              icon={cartIcon}\n              limit={stackLimit}\n              shouldReduceMotion={shouldReduceMotion}\n              spread={stackSpread}\n            />\n          </div>\n        </div>\n\n        <div className=\"min-w-0 text-right\">\n          <span aria-live=\"polite\" className=\"sr-only\">\n            {cart.length} items in cart. Total {total} {currency}.\n          </span>\n\n          <p className=\"text-xs font-medium text-muted-foreground\">{cartLabel}</p>\n\n          <NumberFlow\n            value={total}\n            locales={locale}\n            aria-label={`${cartLabel} ${total}`}\n            format={{\n              style: \"currency\",\n              currency,\n              currencyDisplay: \"narrowSymbol\",\n              minimumFractionDigits: 2,\n            }}\n            className=\"\n              mt-1 block\n              text-2xl font-medium\n              tracking-[-0.025em]\n              tabular-nums\n              sm:text-3xl\n            \"\n          />\n        </div>\n      </div>\n\n      {flights.length > 0\n        ? createPortal(\n            flights.map((flight) => (\n              <FlyingProduct\n                key={flight.id}\n                duration={flightDuration}\n                flight={flight}\n                path={flightPath}\n                onComplete={() => finishFlight(flight)}\n              />\n            )),\n            document.body,\n          )\n        : null}\n    </div>\n  );\n}\n\nexport function CartIcon({ className }: { className?: string }) {\n  return (\n    <svg\n      xmlns=\"http://www.w3.org/2000/svg\"\n      className={className}\n      x=\"0px\"\n      y=\"0px\"\n      width=\"12px\"\n      height=\"12px\"\n      viewBox=\"0 0 18 18\"\n    >\n      <path\n        d=\"M1.75 1.75L3.10101 2.088C3.49401 2.186 3.78899 2.51199 3.84799 2.91299L4.92731 10.25\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        fill=\"none\"\n      ></path>\n      <path\n        d=\"M15.25 13.25H4.75C3.9216 13.25 3.25 12.5784 3.25 11.75C3.25 10.9216 3.9216 10.25 4.75 10.25H13.0496C13.4701 10.25 13.8457 9.98691 13.9894 9.59171L15.2618 6.09171C15.4989 5.43951 15.0159 4.75 14.322 4.75H4.11801\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        fill=\"none\"\n      ></path>\n      <path\n        d=\"M4 17C4.552 17 5 16.552 5 16C5 15.448 4.552 15 4 15C3.448 15 3 15.448 3 16C3 16.552 3.448 17 4 17Z\"\n        fill=\"currentColor\"\n        data-color=\"color-2\"\n      ></path>\n      <path\n        d=\"M14 17C14.552 17 15 16.552 15 16C15 15.448 14.552 15 14 15C13.448 15 13 15.448 13 16C13 16.552 13.448 17 14 17Z\"\n        fill=\"currentColor\"\n        data-color=\"color-2\"\n      ></path>\n    </svg>\n  );\n}\n\nfunction PlusIcon({ className }: { className?: string }) {\n  return (\n    <svg aria-hidden=\"true\" className={className} fill=\"none\" viewBox=\"0 0 24 24\">\n      <path d=\"M12 5V19M5 12H19\" stroke=\"currentColor\" strokeLinecap=\"round\" strokeWidth=\"2\" />\n    </svg>\n  );\n}\n\nfunction CheckIcon({ className }: { className?: string }) {\n  return (\n    <svg aria-hidden=\"true\" className={className} fill=\"none\" viewBox=\"0 0 24 24\">\n      <path\n        d=\"M5 12.5L9.25 16.5L19 7\"\n        stroke=\"currentColor\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        strokeWidth=\"2\"\n      />\n    </svg>\n  );\n}\n","type":"registry:ui"}],"docs":"The default catalog expects product images at public/images/add-to-cart/image1.png through image8.png. Copy the documented assets or pass custom items with your own image paths.","categories":["ecommerce","interaction","animation"],"type":"registry:ui"}