Escaneo y rutas
Copyable Code
Código de identificación con botón de copiar al lado (patrón de ZasExpress). No propaga el clic: dentro de una fila o enlace no navega.
Dependencias: lucide-react
Uso
Notas
Si el navegador no deja copiar, llama a `onCopyError`: ahí va el toast de la app. También se exporta `CopyButton` suelto.
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 copyable-codeVer el código
'use client';
import { cn } from '@/lib/utils';
import { Check, Copy } from 'lucide-react';
import { MouseEvent, ReactNode, useEffect, useRef, useState } from 'react';
export interface CopyButtonProps {
value: string;
/** Texto del tooltip y de lectores de pantalla. */
label?: string;
/** Se llama si el navegador no deja copiar (sin permiso o contexto http); aquí va el toast de la app. */
onCopyError?: () => void;
className?: string;
}
/**
* Copia `value` al portapapeles con un clic (patrón de zasexpress). No propaga
* el clic: dentro de una fila o un enlace no dispara su navegación.
*/
export function CopyButton({
value,
label = 'Copiar código',
onCopyError,
className,
}: CopyButtonProps) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const handleCopy = async (e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
try {
await navigator.clipboard.writeText(value);
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), 2000);
} catch {
onCopyError?.();
}
};
return (
<button
type='button'
onClick={handleCopy}
title={copied ? 'Copiado' : label}
aria-label={copied ? 'Copiado' : label}
className={cn(
'inline-flex shrink-0 items-center justify-center rounded p-0.5 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-700 dark:hover:text-gray-200',
className,
)}
>
{copied ? (
<Check className='h-3.5 w-3.5 text-green-500' />
) : (
<Copy className='h-3.5 w-3.5' />
)}
</button>
);
}
export interface CopyableCodeProps {
value: string | null | undefined;
/** Contenido a mostrar en lugar de `value` (p. ej. un enlace). */
children?: ReactNode;
label?: string;
onCopyError?: () => void;
className?: string;
}
/**
* Código de identificación con su botón de copiar al lado. Sin valor no
* pinta botón (solo `children`, o nada).
*/
export function CopyableCode({
value,
children,
label,
onCopyError,
className,
}: CopyableCodeProps) {
if (!value) return <>{children ?? null}</>;
return (
<span className={cn('inline-flex min-w-0 items-center gap-1', className)}>
{children ?? value}
<CopyButton
value={value}
label={label}
onCopyError={onCopyError}
/>
</span>
);
}