Escaneo y rutas
Option Card
Card de opción con ilustración Lottie: el selector de tipo de carga de ZasExpress y el de «Crear ruta» de Distribuidor.
Dependencias: lottie-web
Con animación en bucle (selector de carga de ZasExpress)
Animación al pasar el cursor (Crear ruta de Distribuidor)
Con icono (Crear ruta de Distribuidor)
Con icono, elegida y deshabilitada
Notas
Base: CargoTypeCard de ZasExpress. Con `restFrame` la animación queda quieta y solo corre con el cursor o el foco de teclado (nunca con prefers-reduced-motion); sin él se reproduce en bucle. `animationSrc` pide el JSON al montar y `lottie-web` se importa dinámico, así no entra en el bundle. Para navegar pasa `as={Link} href`. Si la animación falla, la card sigue funcionando sin ilustración.
Instalación
Con la CLI de zasui (ver Introducción): instala el componente con sus dependencias y queda listo para usar.
pnpm dlx @medialityc/zasui add option-cardVer el código
'use client';
import { cn } from '@/lib/utils';
import type { AnimationItem } from 'lottie-web';
import React, { useCallback, useEffect, useRef, useState } from 'react';
export interface OptionCardProps extends Omit<
React.ComponentPropsWithoutRef<'button'>,
'title'
> {
title: string;
subtitle?: string;
description?: string;
badge?: string;
/** Elemento a pintar: `button` por defecto; pasa `Link` de next/link junto a `href` para navegar. */
as?: React.ElementType;
href?: string;
/** Lottie ya cargado (JSON). Alternativa a `animationSrc`. */
animationData?: object;
/** Lottie servido desde `public/`: se pide al montar y no entra en el bundle. */
animationSrc?: string;
/**
* Fotograma que se muestra quieto. Con él la animación solo corre con el cursor
* o el foco de teclado encima; sin él se reproduce en bucle, como en ZasExpress.
*/
restFrame?: number;
/** Ilustración a todo el ancho de la card (escenas horizontales) en vez de 192 × 192. */
wide?: boolean;
/** Color de borde y hover, p. ej. `border-blue-200 hover:border-blue-400/60`. */
borderClasses?: string;
/** Icono o ilustración propia en lugar de la animación. */
iconSlot?: React.ReactNode;
/** Marca la card como elegida (anillo de acento + aria-pressed). */
selected?: boolean;
/** Texto que explica por qué está deshabilitada (aria-describedby). */
describedBy?: string;
/** Etiqueta accesible, útil cuando el título no basta. */
ariaLabel?: string;
}
const lottieCache = new Map<string, Promise<object>>();
/** Pide el JSON y el motor de Lottie antes de que la card se monte (p. ej. al cargar la página que abre el modal). */
export function preloadLottie(src?: string) {
void import('lottie-web');
if (!src) return;
if (!lottieCache.has(src)) {
const request = fetch(src).then((r) => {
if (!r.ok) throw new Error(`${src}: ${r.status}`);
return r.json();
});
request.catch(() => lottieCache.delete(src));
lottieCache.set(src, request);
}
}
// Misma base que la `CargoTypeCard` de ZasExpress; el anillo de foco usa focus-visible
// y color pleno para que se vea con teclado sin salir al hacer clic.
const BASE_CARD_CLASSES =
'group relative isolate overflow-hidden transition-all duration-300 border rounded-xl p-5 flex flex-col gap-3 shadow-sm hover:shadow-lg hover:-translate-y-0.5 cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-primary bg-white/95 backdrop-blur-sm dark:bg-gray-900/60 dark:border-gray-700 motion-reduce:transition-none motion-reduce:hover:translate-y-0';
/**
* Card de opción con ilustración Lottie: el selector de tipo de carga de ZasExpress
* y el de «Nuevo movimiento» de Distribuidor. Base: `CargoTypeCard`.
*/
export function OptionCard({
title,
subtitle,
description,
badge,
as,
animationData,
animationSrc,
restFrame,
wide = false,
borderClasses = '',
iconSlot,
selected = false,
disabled = false,
describedBy,
ariaLabel,
className,
onMouseEnter,
onMouseLeave,
onFocus,
onBlur,
...props
}: OptionCardProps) {
const Component = as ?? 'button';
const containerRef = useRef<HTMLDivElement>(null);
const animationRef = useRef<AnimationItem | null>(null);
const hovered = useRef(false);
const focused = useRef(false);
const [mounted, setMounted] = useState(false);
// Animación de aparición (fade + scale + y), como en ZasExpress.
useEffect(() => {
const frame = requestAnimationFrame(() => setMounted(true));
return () => cancelAnimationFrame(frame);
}, []);
useEffect(() => {
if (iconSlot || (!animationData && !animationSrc)) return;
let cancelled = false;
const load = async () => {
const [data, lottie] = await Promise.all([
animationData ??
(preloadLottie(animationSrc), lottieCache.get(animationSrc!)!),
import('lottie-web'),
]);
if (cancelled || !containerRef.current) return;
const animation = lottie.default.loadAnimation({
container: containerRef.current,
renderer: 'svg',
loop: true,
autoplay: restFrame === undefined,
animationData: data,
});
if (restFrame !== undefined) animation.goToAndStop(restFrame, true);
animationRef.current = animation;
};
// Sin animación la opción sigue funcionando: solo se pierde la ilustración.
load().catch(() => {});
return () => {
cancelled = true;
animationRef.current?.destroy();
animationRef.current = null;
};
}, [animationData, animationSrc, restFrame, iconSlot]);
// Una sola fuente de verdad: corre si hay cursor o foco; para solo cuando no queda ninguno.
const sync = useCallback(() => {
const animation = animationRef.current;
if (!animation || restFrame === undefined) return;
const reduced = window.matchMedia(
'(prefers-reduced-motion: reduce)',
).matches;
if ((hovered.current || focused.current) && !reduced) {
animation.goToAndPlay(restFrame, true);
} else {
animation.goToAndStop(restFrame, true);
}
}, [restFrame]);
return (
<Component
{...(Component === 'button' ? { type: 'button' } : {})}
{...props}
disabled={disabled}
aria-pressed={as ? undefined : selected}
aria-current={as && selected ? 'true' : undefined}
aria-disabled={disabled || undefined}
aria-label={ariaLabel}
aria-describedby={describedBy}
onMouseEnter={(e: React.MouseEvent<HTMLButtonElement>) => {
hovered.current = true;
sync();
onMouseEnter?.(e);
}}
onMouseLeave={(e: React.MouseEvent<HTMLButtonElement>) => {
hovered.current = false;
sync();
onMouseLeave?.(e);
}}
onFocus={(e: React.FocusEvent<HTMLButtonElement>) => {
focused.current = e.currentTarget.matches(':focus-visible');
sync();
onFocus?.(e);
}}
onBlur={(e: React.FocusEvent<HTMLButtonElement>) => {
focused.current = false;
sync();
onBlur?.(e);
}}
className={cn(
BASE_CARD_CLASSES,
borderClasses,
selected && 'border-primary/70 ring-primary/50 ring-2',
mounted
? 'translate-y-0 scale-100'
: 'translate-y-2 scale-[0.97] opacity-0',
// La opacidad final se calcula en un solo sitio para que el estado
// deshabilitado no compita con la animación de entrada.
mounted && (disabled ? 'opacity-50' : 'opacity-100'),
// Sin hover físico ni halo cuando la card no se puede elegir.
disabled && 'cursor-not-allowed hover:translate-y-0 hover:shadow-sm',
className,
)}
style={{ transitionProperty: 'opacity, transform, box-shadow' }}
>
{/* Halo decorativo muy sutil */}
{!disabled && (
<div className='pointer-events-none absolute inset-0 opacity-0 transition-opacity duration-500 group-hover:opacity-100'>
<div className='from-primary/10 to-primary/30 absolute -inset-px rounded-xl bg-linear-to-br via-transparent blur-sm' />
</div>
)}
<div className='grid w-full items-center justify-center gap-3'>
<div
className={cn(
'group-hover:ring-primary/20 relative flex h-48 items-center justify-center rounded-lg bg-linear-to-br from-white/30 to-white/10 ring-1 ring-transparent transition-all dark:from-white/10 dark:to-white/5',
wide ? 'w-full' : 'w-48',
)}
>
{/* Glow animado al hover */}
<div className='from-primary/10 via-primary/5 absolute inset-0 rounded-lg bg-linear-to-br to-transparent opacity-0 transition-opacity duration-500 group-hover:opacity-100' />
<div
className={cn(
'flex h-full items-center justify-center transition-transform group-hover:scale-105 motion-reduce:transition-none motion-reduce:group-hover:scale-100',
wide ? 'w-full' : 'w-48',
)}
>
{iconSlot ?? (
<div
ref={containerRef}
aria-hidden='true'
className='h-full w-full'
/>
)}
</div>
</div>
<div className='flex flex-col text-center'>
<span className='flex items-center justify-center gap-2 text-xl font-semibold tracking-tight'>
{title}
<span className='bg-primary/60 h-1 w-1 animate-pulse rounded-full motion-reduce:animate-none' />
</span>
{subtitle && (
<span className='text-[11px] font-medium tracking-wide text-gray-500 uppercase dark:text-gray-400'>
{subtitle}
</span>
)}
</div>
</div>
{description && (
<p className='mt-1 text-center text-xs leading-relaxed text-gray-600/90 dark:text-gray-400'>
{description}
</p>
)}
{badge && (
<span className='from-primary/20 to-primary/40 absolute top-2 right-2 rounded-full border border-white/40 bg-linear-to-r px-2 py-0.5 text-[10px] font-medium text-gray-700 shadow-sm backdrop-blur-sm dark:border-white/10 dark:text-gray-200'>
{badge}
</span>
)}
</Component>
);
}