Añadir al carrito con punto volador
Un punto sale del botón, vuela en arco hasta el carrito, el icono rebota y el contador suma.
Cuaderno de bitácora$280 MXN
Código completo
Es exactamente el archivo que se descarga. Cópialo a tu proyecto y úsalo.
"use client";
import { useRef, useState, type CSSProperties } from "react";
/** Botón de añadir al carrito: un punto sale del botón, vuela en arco hasta el carrito, el icono rebota y el contador suma. React + TypeScript, sin dependencias. */
export type CarritoVueloProps = {
product?: string;
price?: string;
initial?: number;
onAdd?: () => void;
className?: string;
style?: CSSProperties;
};
const CSS = `
.gcmcv-root { box-sizing: border-box; position: relative; display: flex; align-items: center; justify-content: space-between; gap: 28px; width: 100%; max-width: 420px; padding: 14px 14px 14px 20px; border: 1px solid #e3e6ee; border-radius: 18px; background: #fff; color: #1f2430; font: 600 15px/1.3 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; box-shadow: 0 1px 2px rgba(20, 30, 50, .06); }
.gcmcv-root *, .gcmcv-root *::before, .gcmcv-root *::after { box-sizing: border-box; }
.gcmcv-root button { font: inherit; -webkit-tap-highlight-color: transparent; }
.gcmcv-root :focus-visible { outline: 3px solid #2563eb; outline-offset: 3px; }
@media (prefers-reduced-motion: reduce) { .gcmcv-root * { animation: none !important; transition-duration: .01ms !important; } }
.gcmcv-name { display: block; font-size: 16px; }
.gcmcv-price { display: block; margin-top: 2px; font-weight: 500; color: #6a7185; }
.gcmcv-add { position: relative; min-height: 48px; padding: 0 22px; border: 0; border-radius: 12px; background: #1f2430; color: #fff; font-weight: 700; cursor: pointer; transition: transform .15s, background .2s; }
.gcmcv-add:hover { background: #343b4f; }
.gcmcv-add:active { transform: scale(.95); }
.gcmcv-cart { position: relative; display: grid; place-items: center; width: 52px; height: 52px; border: 1px solid #e3e6ee; border-radius: 14px; background: #f7f8fb; color: #1f2430; }
.gcmcv-cart[data-bump="true"] { animation: gcmcv-bump .5s cubic-bezier(.34, 1.56, .64, 1); }
.gcmcv-count { position: absolute; top: -8px; right: -8px; min-width: 22px; height: 22px; padding: 0 6px; display: grid; place-items: center; border-radius: 999px; background: #ff4d4f; color: #fff; font: 700 12px/1 ui-sans-serif, sans-serif; box-shadow: 0 0 0 3px #fff; font-variant-numeric: tabular-nums; }
.gcmcv-dot { position: fixed; z-index: 50; width: 14px; height: 14px; margin: -7px 0 0 -7px; border-radius: 50%; background: #ff4d4f; pointer-events: none; box-shadow: 0 0 0 4px rgba(255, 77, 79, .25); }
@keyframes gcmcv-bump { 0% { transform: scale(1); } 40% { transform: scale(1.22) rotate(-6deg); } 100% { transform: scale(1); } }`;
export function CarritoVuelo({ product = "Cuaderno de bitácora", price = "$280 MXN", initial = 0, onAdd, className = "", style }: CarritoVueloProps) {
const [count, setCount] = useState(initial);
const [bump, setBump] = useState(false);
const addRef = useRef<HTMLButtonElement>(null);
const cartRef = useRef<HTMLSpanElement>(null);
function add() {
onAdd?.();
const from = addRef.current?.getBoundingClientRect();
const to = cartRef.current?.getBoundingClientRect();
const finish = () => {
setCount((value) => value + 1);
setBump(true);
window.setTimeout(() => setBump(false), 520);
};
if (!from || !to || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
finish();
return;
}
const dot = document.createElement("span");
dot.className = "gcmcv-dot";
const sx = from.left + from.width / 2, sy = from.top + from.height / 2;
const ex = to.left + to.width / 2, ey = to.top + to.height / 2;
dot.style.left = `${sx}px`;
dot.style.top = `${sy}px`;
document.body.appendChild(dot);
const lift = -Math.max(60, Math.abs(ex - sx) * 0.35);
const anim = dot.animate(
[
{ transform: "translate(0, 0) scale(1)", offset: 0 },
{ transform: `translate(${(ex - sx) * 0.5}px, ${(ey - sy) * 0.5 + lift}px) scale(1.1)`, offset: 0.5 },
{ transform: `translate(${ex - sx}px, ${ey - sy}px) scale(.4)`, offset: 1 },
],
{ duration: 650, easing: "cubic-bezier(.45, 0, .55, 1)" },
);
anim.onfinish = () => {
dot.remove();
finish();
};
}
return (
<div className={`gcmcv-root ${className}`} style={style}>
<style>{CSS}</style>
<div>
<span className="gcmcv-name">{product}</span>
<span className="gcmcv-price">{price}</span>
</div>
<button ref={addRef} className="gcmcv-add" type="button" onClick={add}>
Añadir
</button>
<span ref={cartRef} className="gcmcv-cart" data-bump={bump ? "true" : undefined} role="img" aria-label={`Carrito, ${count} productos`}>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M3 4h2l2.4 11.2a1 1 0 0 0 1 .8h8.8a1 1 0 0 0 1-.8L20 8H6" />
<circle cx="9.5" cy="20" r="1.2" />
<circle cx="17" cy="20" r="1.2" />
</svg>
{count > 0 ? <span className="gcmcv-count" aria-hidden="true">{count}</span> : null}
</span>
</div>
);
}
Úsalo en tu proyecto
Instálalo con la CLI de shadcn.
npx shadcn@latest add https://www.gassierconsulting.com/r/carrito-vueloEjemplo de uso de Añadir al carrito con punto volador
Después de copiar carrito-vuelo.tsx a tu proyecto, impórtalo y colócalo donde lo necesites.
import { CarritoVuelo } from "./carrito-vuelo";
export default function Ejemplo() {
return <CarritoVuelo product="Ejemplo" />;
}Propiedades de CarritoVuelo
CarritoVuelo acepta 6 propiedades: todas son opcionales y tienen un valor por defecto, así que funciona sin configurar nada.
| Propiedad | Tipo | Descripción |
|---|---|---|
product? | string | Opcional. |
price? | string | Opcional. |
initial? | number | Opcional. |
onAdd? | () => void | Opcional. |
className? | string | Opcional. |
style? | CSSProperties | Opcional. |
Accesibilidad y rendimiento
El archivo tiene 94 líneas (5 KB) y define 1 animación con @keyframes. Esto es lo que hace Añadir al carrito con punto volador por quien lo usa:
- Detecta prefers-reduced-motion y baja o quita el movimiento cuando la persona lo pide.
- Muestra un anillo de foco visible al navegar con teclado (:focus-visible).
- Declara roles ARIA para lectores de pantalla: img.
- Es un componente de cliente de Next.js: incluye la directiva "use client".